Assigning custom user IDs
This feature allows you to change the default SuperTokens user ID (UUID v4) to a value that you prefer. There are two primary use cases for this:
- Use case 1: During migration of users
- Use case 2: If you prefer a different user ID format than the default one.
The way this feature works is that SuperTokens will store and manage the user ID mapping in the SuperTokens core. So when that users logs in, you will get back the mapped (the custom) user ID instead of the SuperTokens user ID.
Features like user roles, user metadata, session will also all work based on the custom user ID.
#
Use case 1: Migration of usersThis topic is better covered under the migration section. The main purpose of this is that you can retain the existing user IDs of your users when migrating them to SuperTokens. This makes it easier to migrate users without having to update the user IDs in your database.
#
Use case 2: If you prefer a different user ID format than the default one.You can call the user ID mapping function post sign up as shown below. It is important to know that user ID mapping can only be done, before there is any other data (session, roles etc) associated with the user.
- NodeJS
- GoLang
- Python
- Other Frameworks
Important
import SuperTokens from "supertokens-node";
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
import Session from "supertokens-node/recipe/session";
import { RecipeUserId } from "supertokens-node";
SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
recipeList: [
ThirdPartyPasswordless.init({
contactMethod: "EMAIL", // This example will work with any contactMethod
flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", // This example will work with any flowType
override: {
functions: (originalImplementation) => {
return {
...originalImplementation,
// override the thirdparty sign in / up API
thirdPartySignInUp: async function (input) {
let response = await originalImplementation.thirdPartySignInUp(input);
if (response.status === "OK") {
let { id, emails } = response.user;
// This is the response from the OAuth 2 provider that contains their tokens or user info.
let providerAccessToken = response.oAuthTokens["access_token"];
let firstName = response.rawUserInfoFromProvider.fromUserInfoAPI!["first_name"];
if (response.createdNewRecipeUser && response.user.loginMethods.length === 1 && input.session === undefined) {
let externalUserId = "<CUSTOM USER ID>"
await SuperTokens.createUserIdMapping({ superTokensUserId: response.user.id, externalUserId })
// we modify the response object to have the custom user ID.
response.user.id = externalUserId
response.user.loginMethods[0].recipeUserId = new RecipeUserId(externalUserId);
}
}
return response;
},
consumeCode: async (input) => {
// First we call the original implementation of consumeCodePOST.
const response = await originalImplementation.consumeCode(input);
// Post sign up response, we check if it was successful
if (response.status === "OK") {
if ("phoneNumber" in response.user) {
const { id, phoneNumbers } = response.user;
} else {
const { id, emails } = response.user;
}
if (response.createdNewRecipeUser && response.user.loginMethods.length === 1 && input.session === undefined) {
let externalUserId = "<CUSTOM USER ID>"
await SuperTokens.createUserIdMapping({ superTokensUserId: response.user.id, externalUserId })
// we modify the response object to have the custom user ID.
response.user.id = externalUserId
response.user.loginMethods[0].recipeUserId = new RecipeUserId(externalUserId);
}
}
return response;
}
}
}
}
}),
Session.init({ /* ... */ })
]
});
import (
"github.com/supertokens/supertokens-golang/recipe/passwordless/plessmodels"
"github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels"
"github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless"
"github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless/tplmodels"
"github.com/supertokens/supertokens-golang/supertokens"
)
func main() {
supertokens.Init(supertokens.TypeInput{
RecipeList: []supertokens.Recipe{
thirdpartypasswordless.Init(tplmodels.TypeInput{
Override: &tplmodels.OverrideStruct{
Functions: func(originalImplementation tplmodels.RecipeInterface) tplmodels.RecipeInterface {
// create a copy of the original function
originalConsumeCode := *originalImplementation.ConsumeCode
originalThirdPartySignInUp := *originalImplementation.ThirdPartySignInUp
// override the thirdparty sign in / up function
(*originalImplementation.ThirdPartySignInUp) = func(thirdPartyID string, thirdPartyUserID string, email string, oAuthTokens map[string]interface{}, rawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider, tenantId string, userContext *map[string]interface{}) (tplmodels.ThirdPartySignInUp, error) {
// TODO: some pre sign in / up logic
resp, err := originalThirdPartySignInUp(thirdPartyID, thirdPartyUserID, email, oAuthTokens, rawUserInfoFromProvider, tenantId, userContext)
if err != nil {
return tplmodels.ThirdPartySignInUp{}, err
}
if resp.OK != nil {
if resp.OK.CreatedNewUser {
externalUserId := "<CUSTOM USER ID>"
_, err := supertokens.CreateUserIdMapping(resp.OK.User.ID, externalUserId, nil, nil)
if err != nil {
return tplmodels.ThirdPartySignInUp{}, err
}
resp.OK.User.ID = externalUserId
}
}
return resp, err
}
// override the passwordless sign in up function
(*originalImplementation.ConsumeCode) = func(userInput *plessmodels.UserInputCodeWithDeviceID, linkCode *string, preAuthSessionID string, tenantId string, userContext supertokens.UserContext) (tplmodels.ConsumeCodeResponse, error) {
// First we call the original implementation of ConsumeCodeUp.
response, err := originalConsumeCode(userInput, linkCode, preAuthSessionID, tenantId, userContext)
if err != nil {
return tplmodels.ConsumeCodeResponse{}, err
}
if response.OK != nil {
if response.OK.CreatedNewUser {
externalUserId := "<CUSTOM USER ID>"
_, err := supertokens.CreateUserIdMapping(response.OK.User.ID, externalUserId, nil, nil)
if err != nil {
return tplmodels.ConsumeCodeResponse{}, err
}
response.OK.User.ID = externalUserId
}
}
return response, nil
}
return originalImplementation
},
},
}),
},
})
}
from supertokens_python import init, InputAppInfo
from supertokens_python.asyncio import create_user_id_mapping
from supertokens_python.recipe import thirdpartypasswordless, session, passwordless
from supertokens_python.recipe.thirdpartypasswordless.interfaces import RecipeInterface, ConsumeCodeOkResult
from supertokens_python.recipe.thirdparty.types import RawUserInfoFromProvider
from typing import Dict, Any, Union
def override_thirdpartypasswordless_functions(original_implementation: RecipeInterface) -> RecipeInterface:
original_thirdparty_sign_in_up = original_implementation.thirdparty_sign_in_up
original_consume_code = original_implementation.consume_code
async def thirdparty_sign_in_up(
third_party_id: str,
third_party_user_id: str,
email: str,
oauth_tokens: Dict[str, Any],
raw_user_info_from_provider: RawUserInfoFromProvider,
tenant_id: str,
user_context: Dict[str, Any]
):
result = await original_thirdparty_sign_in_up(third_party_id, third_party_user_id, email, oauth_tokens, raw_user_info_from_provider, tenant_id, user_context)
# user object contains the ID and email of the user
user = result.user
print(user)
# This is the response from the OAuth 2 provider that contains their tokens or user info.
provider_access_token = result.oauth_tokens["access_token"]
print(provider_access_token)
if result.raw_user_info_from_provider.from_user_info_api is not None:
first_name = result.raw_user_info_from_provider.from_user_info_api["first_name"]
print(first_name)
if result.created_new_user:
external_user_id = "<CUSTOM USER ID>"
await create_user_id_mapping(result.user.user_id, external_user_id)
result.user.user_id = external_user_id
return result
async def consume_code(
pre_auth_session_id: str,
user_input_code: Union[str, None],
device_id: Union[str, None],
link_code: Union[str, None],
tenant_id: str,
user_context: Dict[str, Any]
):
# First we call the original implementation of consumeCodePOST.
result = await original_consume_code(pre_auth_session_id, user_input_code, device_id, link_code, tenant_id, user_context)
# Post sign up response, we check if it was successful
if isinstance(result, ConsumeCodeOkResult):
id = result.user.user_id
print(id)
if result.user.phone_number is not None:
phone_number = result.user.phone_number
print(phone_number)
else:
email = result.user.email
print(email)
if result.created_new_user:
external_user_id = "<CUSTOM USER ID>"
await create_user_id_mapping(result.user.user_id, external_user_id)
result.user.user_id = external_user_id
return result
original_implementation.thirdparty_sign_in_up = thirdparty_sign_in_up
original_implementation.consume_code = consume_code
return original_implementation
init(
app_info=InputAppInfo(api_domain="...", app_name="...", website_domain="..."),
framework='...',
recipe_list=[
thirdpartypasswordless.init(
contact_config=passwordless.ContactConfig(
contact_method="EMAIL", # This example will work with any contactMethod
),
flow_type="USER_INPUT_CODE_AND_MAGIC_LINK", # This example will work with any flowType
override=thirdpartypasswordless.InputOverrideConfig(
functions=override_thirdpartypasswordless_functions
),
providers=[]
),
session.init(),
]
)