Skip to main content

If you are using our backend SDK that is lesser than the following versions, please visit the older documentation link here.

User Creation without password hashes

caution

The recommended method for migrating users to SuperTokens is by importing users with their password hashes. You should only use the following method if you do not have access to your user's password hashes and still have access to your previous identity provider.

SuperTokens also supports the "just in time" user migration strategy for when password hashes cannot be exported from your legacy provider.

We will need to make the following customizations to SuperTokens authentication flows to support this strategy:

  • Step 1) Prevent signups from users who exist in the external provider.
    • To prevent duplicate accounts from being created, we block signups from users who have existing accounts with the external provider.
  • Step 2) Create a SuperTokens account for users trying to sign in if they have an account with the external provider.
    • We will modify the signin flow to check if the user signing in has an existing account with the external provider and not with SuperTokens. If their input credentials are valid, we create a SuperTokens user and import their user data.
  • Step 3) Create a SuperTokens account for users who have an account with the external provider but have forgotten their password.
    • Some users who have an account with the external provider and not with SuperTokens may have forgotten their passwords and will trigger the password reset flow. Since SuperTokens requires an existing account to send the reset password email to, we will need to modify the password reset flow to check that if the user needs to be migrated. If they do, we create a SuperTokens account with a temporary password, import their user data and continue the password reset flow.
    • To ensure that users can only signin once they succesfully reset their passwords we add the isUsingTemporaryPassword flag to the account's metadata. We will also modify the signin flow to block signins from accounts with this metadata.
  • Step 4) Remove the isUsingTemporaryPassword flag on successful password reset
    • Once the password has been successfully reset we check if the user has the isUsingTemporaryPassword flag set in the metadata. If they do we will clear the flag from the user's metadata.
  • Step 5) Update the login flow to account for the isUsingTemporaryPassword flag
    • We also update the login flow to prevent signins from accounts who have the isUsingTemporaryPassword flag and if their input password does not match the one in the legacy auth provider. This is done so that users who started the password reset flow are forced to finish it.

Step 1) Prevent signups from users who exist in the external provider#

To implement this change we will override the api that handles email-password login when initializing the recipe on the backend.

import EmailPassword from "supertokens-node/recipe/emailpassword"

EmailPassword.init({
override: {
apis: (originalImplementation) => {
return {
...originalImplementation,
signUpPOST: async function (input) {
let email = input.formFields.find((field) => field.id === "email")!.value as string;
// Check if the user signing in exists in the external provider
if (await doesUserExistInExternalProvider(email)) {
// Return status "EMAIL_ALREADY_EXISTS_ERROR" since the user already exists in the external provider
return {
status: "EMAIL_ALREADY_EXISTS_ERROR"
}
}
return originalImplementation.signUpPOST!(input);
},
}
},
}
})

async function doesUserExistInExternalProvider(email: string): Promise<boolean> {
// TODO: check if user with the input email exists in the external provider
return false;
}

We modify the signUpPOST API to first check if the user signing up has an account with the external provider. If they do we return a EMAIL_ALREADY_EXISTS_ERROR

Step 2) Create a SuperTokens account for users trying to sign in if they have an account with the external provider#

To implement this flow we will override the API that handles email-password login when initializing the recipe on the backend.

import SuperTokens from "supertokens-node"
import EmailPassword from "supertokens-node/recipe/emailpassword"
import EmailVerification from "supertokens-node/recipe/emailverification"
import { RecipeUserId } from "supertokens-node";

EmailPassword.init({
override: {
apis: (originalImplementation) => {
return {
...originalImplementation,
signInPOST: async function (input) {
// Check if an email-password user with the input email exists in SuperTokens
let email = input.formFields.find((field) => field.id === "email")!.value as string;
let password = input.formFields.find((field) => field.id === "password")!.value as string;
let supertokensUsersWithSameEmail = await SuperTokens.listUsersByAccountInfo(input.tenantId, {
email: email
}, undefined, input.userContext);
let emailPasswordUser = supertokensUsersWithSameEmail.find(u => {
return u.loginMethods.find(lM => lM.hasSameEmailAs(email) && lM.recipeId === "emailpassword") !== undefined;
})

if (emailPasswordUser === undefined) {
// EmailPassword user with the input email does not exist in SuperTokens
// Check if the input credentials are valid in the external provider
let legacyUserInfo = await validateAndGetUserInfoFromExternalProvider(email, password)
if (legacyUserInfo === undefined) {
// credentials are incorrect
return {
status: "WRONG_CREDENTIALS_ERROR"
}
}

// Call the signup function to create a new SuperTokens user.
let signUpResponse = await EmailPassword.signUp(input.tenantId, email, password, undefined, input.userContext);
if (signUpResponse.status !== "OK") {
throw new Error("Should never come here")
}

// Map the external provider's userId to the SuperTokens userId
await SuperTokens.createUserIdMapping({ superTokensUserId: signUpResponse.user.id, externalUserId: legacyUserInfo.user_id })

// Set the userId in the response to use the provider's userId
signUpResponse.user.id = legacyUserInfo.user_id
signUpResponse.user.loginMethods[0].recipeUserId = new RecipeUserId(legacyUserInfo.user_id);
signUpResponse.recipeUserId = new RecipeUserId(legacyUserInfo.user_id);

// We will also need to set the email verification status of the user
if (legacyUserInfo.isEmailVerified) {
// Generate an email verification token for the user
let generateEmailVerificationTokenResponse = await EmailVerification.createEmailVerificationToken(input.tenantId, signUpResponse.recipeUserId, email, input.userContext);

if (generateEmailVerificationTokenResponse.status === "OK") {
// Verify the user's email
await EmailVerification.verifyEmailUsingToken("public", generateEmailVerificationTokenResponse.token, undefined, input.userContext);
}
}
}

return originalImplementation.signInPOST!(input)
},
}
},
}
})

async function validateAndGetUserInfoFromExternalProvider(email: string, password: string): Promise<{
user_id: string,
isEmailVerified: boolean
} | undefined> {
// TODO: Validate the input credentials against the external authentication provider. If the credentials are valid return the user info.
return undefined
}

The code above overrides the signInPOST API with the following changes to achieve "just in time" migration:

  • The first step is to determine if the user signing in needs to be migrated or not. We do this by checking if a user with the input email exists in the external auth provider and SuperTokens. If the user exists in the external auth provider and does not exist SuperTokens, we can determine that this user needs to be migrated.
  • The next step is to validate the input credentials against the external provider. If the credentials are invalid we will throw a WRONG_CREDENTIALS_ERROR. If the credentials are valid we can call the SuperTokens login function with the input credentials to create a new SuperTokens user.
  • We now map the external userId to the SuperTokens userId. This will allow SuperTokens functions to refrence the user with the external userId.
  • Finally, depending on the email verification status of the user in the external provider we will also verify the user's email in SuperTokens.

Step 3) Create a SuperTokens account for users who have an account with the external provider but have forgotten their password.#

Some users who do not have an account with SuperTokens but have an existing account with the external provider may have forgotten their passwords and will initiate a password reset. Since password resets require an existing SuperTokens account to send the password reset email to, the password reset flow will need to be modified to create a SuperTokens account if the user exists in the external provider.

import SuperTokens from "supertokens-node"
import EmailPassword from "supertokens-node/recipe/emailpassword"
import EmailVerification from "supertokens-node/recipe/emailverification"
import UserMetadata from "supertokens-node/recipe/usermetadata"
import { RecipeUserId } from "supertokens-node";

EmailPassword.init({
override: {
apis: (originalImplementation) => {
return {
...originalImplementation,
// Add overrides from the previous step
generatePasswordResetTokenPOST: async (input) => {
// Retrieve the email from the input
let email = input.formFields.find(i => i.id === "email")!.value as string;

// check if user exists in SuperTokens
let supertokensUsersWithSameEmail = await SuperTokens.listUsersByAccountInfo(input.tenantId, {
email
}, undefined, input.userContext);
let emailPasswordUser = supertokensUsersWithSameEmail.find(u => {
return u.loginMethods.find(lM => lM.hasSameEmailAs(email) && lM.recipeId === "emailpassword") !== undefined;
})

if (emailPasswordUser === undefined) {
// User does not exist in SuperTokens
// Check if the user exists in the legacy provider and retrieve their data
let legacyUserData = await retrieveUserDataFromExternalProvider(email);
if (legacyUserData) {
// create a SuperTokens account for the user with a temporary password
let tempPassword = await generatePassword();
let signupResponse = await EmailPassword.signUp(input.tenantId, email, tempPassword, undefined, input.userContext);

if (signupResponse.status === "OK") {

// If user is succesfully created we will map the legacy id to their SuperTokens Id.
await SuperTokens.createUserIdMapping({
superTokensUserId: signupResponse.user.id,
externalUserId: legacyUserData.user_id
})
signupResponse.user.id = legacyUserData.user_id
signupResponse.user.loginMethods[0].recipeUserId = new RecipeUserId(legacyUserData.user_id);
signupResponse.recipeUserId = new RecipeUserId(legacyUserData.user_id);

// We will also need to set the email verification status of the user
if (legacyUserData.isEmailVerified) {
// Generate an email verification token for the user
let generateEmailVerificationTokenResponse = await EmailVerification.createEmailVerificationToken(input.tenantId, signupResponse.recipeUserId, email, input.userContext);

if (generateEmailVerificationTokenResponse.status === "OK") {
// Verify the user's email
await EmailVerification.verifyEmailUsingToken("public", generateEmailVerificationTokenResponse.token, undefined, input.userContext);
}
}

// We also need to identify that the user is using a temporary password. We do through the userMetadata recipe
UserMetadata.updateUserMetadata(legacyUserData.user_id, { isUsingTemporaryPassword: true })
} else {
throw new Error("Should never come here")
}
}
}
return await originalImplementation.generatePasswordResetTokenPOST!(input);
},
}
}
}
})

async function generatePassword(): Promise<string> {
// TODO: generate a random password
return ""
}

async function retrieveUserDataFromExternalProvider(email: string): Promise<{
user_id: string,
isEmailVerified: boolean
} | undefined> {
// TODO: retrieve user data if a user with the input email exists in the external provider.
return undefined;
}

The code above overrides the generatePasswordResetTokenPOST API. This is the first step in the password reset flow and is responsible for generating the password reset token to be sent with the reset password email.

  • Similar to the previous step, we need to determine whether to migrate the user or not.
  • The next step is to create a SuperTokens account with a temporary password, the password can be a random string since it will be reset by the user when they complete the reset password flow.
  • We now map the external userId(the userId from the external provider) to the SuperTokens userId. This will allow SuperTokens functions to refrence the user with the external userId.
  • Depending on the email verification status of the user in the external provider we will also verify the user's email in SuperTokens.
  • We assign the isUsingTemporaryPassword flag to user's metadata since the account was generated with a temporary password. This is done to prevent signins until the password is successfully reset.

Step 4) Remove the isUsingTemporaryPassword flag on successful password reset#

If the password reset flow is successfully completed we will need to check if the user has isUsingTemporaryPassword set in their metadata and remove it if it exists.

import EmailPassword from "supertokens-node/recipe/emailpassword"
import UserMetadata from "supertokens-node/recipe/usermetadata"

EmailPassword.init({
override: {
apis: (originalImplementation) => {
return {
...originalImplementation,
// TODO: implementation details in previous step
passwordResetPOST: async function (input) {
let response = await originalImplementation.passwordResetPOST!(input);
if (response.status === "OK") {
let usermetadata = await UserMetadata.getUserMetadata(response.user.id, input.userContext)
if (usermetadata.status === "OK" && usermetadata.metadata.isUsingTemporaryPassword) {
// Since the password reset we can remove the isUsingTemporaryPassword flag
await UserMetadata.updateUserMetadata(response.user.id, { isUsingTemporaryPassword: null })
}
}
return response
}
}
}
}
})

The code above overrides the passwordResetPOST API and is a continuation of the password reset flow:

  • On a successful password reset we check if the user has the isUsingTemporaryPassword flag set in their metadata and remove it If it exists.

Step 5) Update the login flow to account for the isUsingTemporaryPassword flag#

Apart from the changes we made in Step 1, we also need to account for users who have a initiated password reset but have not completed the flow. There are two cases we need to handle:

  • Prevent signin from accounts that have temporary passwords.
    • If, for any reason, the user tries to sign into their account with the temporary password, then the login method should be blocked.
  • If a user initiates a password reset but remembers their password, they should be able to sign in.
    • In this case the user should be able to login and the database should be updated to reflect the new password.
import SuperTokens from "supertokens-node";
import EmailPassword from "supertokens-node/recipe/emailpassword"
import EmailVerification from "supertokens-node/recipe/emailverification";
import UserMetadata from "supertokens-node/recipe/usermetadata";
import { RecipeUserId } from "supertokens-node";

EmailPassword.init({
override: {
apis: (originalImplementation) => {
return {
...originalImplementation,
signInPOST: async function (input) {
// Check if an email-password user with the input email exists in SuperTokens
let email = input.formFields.find((field) => field.id === "email")!.value as string;
let password = input.formFields.find((field) => field.id === "password")!.value as string;
let supertokensUsersWithSameEmail = await SuperTokens.listUsersByAccountInfo(input.tenantId, {
email: email
}, undefined, input.userContext);
let emailPasswordUser = supertokensUsersWithSameEmail.find(u => {
return u.loginMethods.find(lM => lM.hasSameEmailAs(email) && lM.recipeId === "emailpassword") !== undefined;
})

if (emailPasswordUser === undefined) {
// EmailPassword user with the input email does not exist in SuperTokens
// Check if the input credentials are valid in the external provider
let legacyUserInfo = await validateAndGetUserInfoFromExternalProvider(email, password)
if (legacyUserInfo === undefined) {
// credentials are incorrect
return {
status: "WRONG_CREDENTIALS_ERROR"
}
}

// Call the signup function to create a new SuperTokens user.
let signUpResponse = await EmailPassword.signUp(input.tenantId, email, password, undefined, input.userContext);
if (signUpResponse.status !== "OK") {
throw new Error("Should never come here")
}

// Map the external provider's userId to the SuperTokens userId
await SuperTokens.createUserIdMapping({ superTokensUserId: signUpResponse.user.id, externalUserId: legacyUserInfo.user_id })
// Set the userId in the response to use the provider's userId
signUpResponse.user.id = legacyUserInfo.user_id
signUpResponse.user.loginMethods[0].recipeUserId = new RecipeUserId(legacyUserInfo.user_id);

// We will also need to set the email verification status of the user
if (legacyUserInfo.isEmailVerified) {
// Generate an email verification token for the user
let generateEmailVerificationTokenResponse = await EmailVerification.createEmailVerificationToken(input.tenantId, signUpResponse.recipeUserId, email, input.userContext);

if (generateEmailVerificationTokenResponse.status === "OK") {
// Verify the user's email
await EmailVerification.verifyEmailUsingToken("public", generateEmailVerificationTokenResponse.token, undefined, input.userContext);
}
}
emailPasswordUser = signUpResponse.user;
}
// Check if the user signing in has a temporary password
let userMetadata = await UserMetadata.getUserMetadata(emailPasswordUser.id, input.userContext)
if (userMetadata.status === "OK" && userMetadata.metadata.isUsingTemporaryPassword) {
// Check if the input credentials are valid in the external provider
let legacyUserInfo = await validateAndGetUserInfoFromExternalProvider(email, password);
if (legacyUserInfo) {
let loginMethod = emailPasswordUser.loginMethods.find(lM => lM.recipeId === "emailpassword" && lM.hasSameEmailAs(email));
// Update the user's password with the correct password
EmailPassword.updateEmailOrPassword({
recipeUserId: loginMethod!.recipeUserId,
password: password,
applyPasswordPolicy: false
})

// Update the user's metadata to remove the isUsingTemporaryPassword flag
UserMetadata.updateUserMetadata(emailPasswordUser.id, { isUsingTemporaryPassword: null })
} else {
return {
status: "WRONG_CREDENTIALS_ERROR"
}
}
}

return originalImplementation.signInPOST!(input)
},
}
},
}
})

async function validateAndGetUserInfoFromExternalProvider(email: string, password: string): Promise<{
user_id: string,
isEmailVerified: boolean
} | undefined> {
// TODO: Validate the input credentials against the external authentication provider. If the credentials are valid return the user info.
return undefined
}

The code above adds the following changes to the signInPOST API:

  • Adds an additional check where if a user exists in SuperTokens, we check if they have the isUsingTemporaryPassword flag set in their metadata.
  • If the flag exists, we check if the input credentials are valid in the external provider. If they are we update the account with the new password and continue the login flow.
  • If the input credentials are invalid in the external provider, we return a WRONG_CREDENTIALS_ERROR.

User migration edge cases that are addressed#

This stratergy takes into account the following edge cases to ensure a smooth migration experience:

  • Users who have not been migrated over to SuperTokens forgets their passwords and tries the password reset flow
    • In this situation, the regular password reset flow will not work since password resets require an existing account.
    • The changes proposed in Step 3 and Step 4 resolve the this edge case.
  • User starts the password reset flow and attempts to sign in with a temporary password
    • If, for any reason, the user tries to sign into their account with the temporary password, then the login method should be blocked.
    • The changes proposed in Step 5 allows for this flow
  • User starts the password reset flow but they remember their password and try to login with the valid password.
    • In this scenario if the user starts the password reset flow, a new SuperTokens account with a temporary password is created. Instead of completing the password reset flow they remember their password and try to sign in. In this case the user should be able to successfully sign in and the account should be updated with the valid password.
    • The changes proposed in Step 5 allows for this flow.

When can I stop using my legacy authentication provider?#

Your migration period could be decided by either of the following factors:

  • A time window (2-3 months) within which "just-in-time" migration is active.
  • A user migration threshold where, after a certain percentage of the userbase is migrated, the migration period ends.

After the migration period ends you have to make the following changes to stop automatic user migration:

  • Remove all migration related override changes in your backend.
  • Take the remaining users' emails and call the signup function with a secure randomized password.
  • Email users encouraging them to go through the password reset flow.