Changes to third party flow
We need to start by maintaining an allow list of emails. You can either store this list in your own database, or then use the metadata feature provided by SuperTokens to store this. This may seem like a strange use case of the user metadata recipe we provide, but it works.
You want to implement the following functions on your backend:
- NodeJS
- GoLang
- Python
- Other Frameworks
Important
import UserMetadata from "supertokens-node/recipe/usermetadata"
async function addEmailToAllowlist(email: string) {
let existingData = await UserMetadata.getUserMetadata("emailAllowList");
let allowList: string[] = existingData.metadata.allowList || [];
allowList = [...allowList, email];
await UserMetadata.updateUserMetadata("emailAllowList", {
allowList
});
}
async function isEmailAllowed(email: string) {
let existingData = await UserMetadata.getUserMetadata("emailAllowList");
let allowList: string[] = existingData.metadata.allowList || [];
return allowList.includes(email);
}
import "github.com/supertokens/supertokens-golang/recipe/usermetadata"
func addEmailToAllowlist(email string) error {
existingData, err := usermetadata.GetUserMetadata("emailAllowList")
if err != nil {
return err
}
allowList := []string{}
allowListFromMetadata, ok := existingData["allowList"].([]string)
if ok {
allowList = allowListFromMetadata
}
allowList = append(allowList, email)
_, err = usermetadata.UpdateUserMetadata("emailAllowList", map[string]interface{}{
"allowList": allowList,
})
return err
}
func isEmailAllowed(email string) (bool, error) {
existingData, err := usermetadata.GetUserMetadata("emailAllowList")
if err != nil {
return false, err
}
allowList := []string{}
allowListFromMetadata, ok := existingData["allowList"].([]string)
if ok {
allowList = allowListFromMetadata
}
for _, allowedEmail := range allowList {
if allowedEmail == email {
return true, nil
}
}
return false, nil
}
from supertokens_python.recipe.usermetadata.asyncio import get_user_metadata, update_user_metadata
from typing import List
async def add_email_to_allow_list(email: str):
metadataResult = await get_user_metadata("emailAllowList")
allow_list: List[str] = metadataResult.metadata["allowList"] if "allowList" in metadataResult.metadata else []
allow_list.append(email)
await update_user_metadata("emailAllowList", {
"allowList": allow_list
})
async def is_email_allowed(email: str):
metadataResult = await get_user_metadata("emailAllowList")
allow_list: List[str] = metadataResult.metadata["allowList"] if "allowList" in metadataResult.metadata else []
return email in allow_list
important
Remember to initialise the user metadata recipe on the backend recipeList
during supertokens.init
.
Multi Tenancy
For a multi tenant setup, you can even store an allow list per tenant. This would allow you to limit sign ups for different emails for different tenants. If you are doing this, then you would also need to pass in the tenantID to the functions above, which you can obtain from the input to the api overrides shown below.
After that, we override the thirdPartySignInUpPOST
API and the thirdPartySignInUp
recipe function to check if the input email is allowed durign sign up. If not allowed, we send back a user friendly message to the frontend.
- NodeJS
- GoLang
- Python
- Other Frameworks
Important
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
import supertokens from "supertokens-node";
ThirdPartyPasswordless.init({
override: {
functions: (originalImplementation) => {
return {
...originalImplementation,
thirdPartySignInUp: async function (input) {
let existingUsers = await supertokens.listUsersByAccountInfo(input.tenantId, {
email: input.email
});
if (existingUsers.length === 0) {
// this means that the email is new and is a sign up
if (!(await isEmailAllowed(input.email))) {
// email is not in allow list, so we disallow
throw new Error("No sign up")
}
}
// We allow the sign in / up operation
return originalImplementation.thirdPartySignInUp(input);
}
}
},
apis: (originalImplementation) => {
return {
...originalImplementation,
thirdPartySignInUpPOST: async function (input) {
try {
return await originalImplementation.thirdPartySignInUpPOST!(input);
} catch (err: any) {
if (err.message === "No sign up") {
// this error was thrown from our function override above.
// so we send a useful message to the user
return {
status: "GENERAL_ERROR",
message: "Sign ups are disabled. Please contact the admin."
}
}
throw err;
}
}
}
}
}
})
import (
"errors"
"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 isEmailAllowed(email string) (bool, error) {
// ... from previous code snippet
return false, nil
}
func main() {
thirdpartypasswordless.Init(tplmodels.TypeInput{
Override: &tplmodels.OverrideStruct{
Functions: func(originalImplementation tplmodels.RecipeInterface) tplmodels.RecipeInterface {
ogThirdPartySignInUp := *originalImplementation.ThirdPartySignInUp
(*originalImplementation.ThirdPartySignInUp) = func(thirdPartyID, thirdPartyUserID, email string, oAuthTokens map[string]interface{}, rawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider, tenantId string, userContext supertokens.UserContext) (tplmodels.ThirdPartySignInUp, error) {
existingUsers, err := thirdpartypasswordless.GetUsersByEmail(tenantId, email)
if err != nil {
return tplmodels.ThirdPartySignInUp{}, err
}
if len(existingUsers) == 0 {
// this means that the email is new and is a sign up
allowed, err := isEmailAllowed(email)
if err != nil {
return tplmodels.ThirdPartySignInUp{}, err
}
if !allowed {
return tplmodels.ThirdPartySignInUp{}, errors.New("No sign up")
}
}
// We allow the sign in / up operation
return ogThirdPartySignInUp(thirdPartyID, thirdPartyUserID, email, oAuthTokens, rawUserInfoFromProvider, tenantId, userContext)
}
return originalImplementation
},
APIs: func(originalImplementation tplmodels.APIInterface) tplmodels.APIInterface {
originalSignInUpPOST := *originalImplementation.ThirdPartySignInUpPOST
(*originalImplementation.ThirdPartySignInUpPOST) = func(provider *tpmodels.TypeProvider, input tpmodels.TypeSignInUpInput, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (tplmodels.ThirdPartySignInUpPOSTResponse, error) {
resp, err := originalSignInUpPOST(provider, input, tenantId, options, userContext)
if err.Error() == "No sign up" {
// this error was thrown from our function override above.
// so we send a useful message to the user
return tplmodels.ThirdPartySignInUpPOSTResponse{
GeneralError: &supertokens.GeneralErrorResponse{
Message: "Sign ups are disabled. Please contact the admin.",
},
}, nil
}
return resp, err
}
return originalImplementation
},
},
})
}
from supertokens_python import init, InputAppInfo
from supertokens_python.types import GeneralErrorResponse
from supertokens_python.recipe import thirdpartypasswordless
from supertokens_python.recipe.thirdpartypasswordless.asyncio import get_users_by_email
from supertokens_python.recipe.thirdpartypasswordless.interfaces import APIInterface, RecipeInterface, ThirdPartySignInUpOkResult, ThirdPartyAPIOptions
from typing import Optional, Dict, Any
from supertokens_python.recipe.thirdparty.provider import Provider, RedirectUriInfo
from supertokens_python.recipe.thirdparty.types import RawUserInfoFromProvider
async def is_email_allowed(email: str):
# from previous code snippet..
return False
def override_thirdpartypasswordless_functions(original_implementation: RecipeInterface):
original_thirdparty_sign_in_up = original_implementation.thirdparty_sign_in_up
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]
) -> ThirdPartySignInUpOkResult:
existing_users = await get_users_by_email(tenant_id, email, user_context)
if (len(existing_users) == 0):
if not await is_email_allowed(email):
raise Exception("No sign up")
# this means this email is new so we allow sign up
return 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)
raise Exception("No sign up")
original_implementation.thirdparty_sign_in_up = thirdparty_sign_in_up
return original_implementation
def override_thirdpartypasswordless_apis(original_implementation: APIInterface):
original_sign_in_up_post = original_implementation.thirdparty_sign_in_up_post
async def thirdparty_sign_in_up_post(
provider: Provider,
redirect_uri_info: Optional[RedirectUriInfo],
oauth_tokens: Optional[Dict[str, Any]],
tenant_id: str,
api_options: ThirdPartyAPIOptions,
user_context: Dict[str, Any]
):
try:
return await original_sign_in_up_post(provider, redirect_uri_info, oauth_tokens, tenant_id, api_options, user_context)
except Exception as e:
if str(e) == "No sign up":
return GeneralErrorResponse("Seems like you already have an account with another method. Please use that instead.")
raise e
original_implementation.thirdparty_sign_in_up_post = thirdparty_sign_in_up_post
return original_implementation
init(
app_info=InputAppInfo(
api_domain="...", app_name="...", website_domain="..."),
framework='...',
recipe_list=[
thirdpartypasswordless.init(
flow_type="USER_INPUT_CODE",
override=thirdpartypasswordless.InputOverrideConfig(
apis=override_thirdpartypasswordless_apis,
functions=override_thirdpartypasswordless_functions
),
)
]
)
thirdPartySignInUpPOST
is called when the user is redirected to the app from the third party provider post login. The API calls the thirdPartySignInUp
recipe function in which we check:
- If there exists a user with the input email, it means they are signing in and so we allow the operation.
- Otherwise, we check if the input email is allowed by calling our
isEmailAllowed
function (which we implemented above). If not allowed, we throw an error with a custom message. - Finally, we override the
thirdPartySignInUpPOST
API to catch this custom error and return a message to the frontend which will be displayed to the user.
We can add emails to the allow list by calling the addEmailToAllowlist
function we implemented above.