Post signin / signup callbacks
#
1) On the frontend- ReactJS
- Angular
- Vue
Important
supertokens-auth-react
SDK and will inject the React components to show the UI. Therefore, the code snippet below refers to the supertokens-auth-react
SDK.This method allows you to fire events immediately after a successful sign in / up. For example to send analytics events post sign in / up.
import SuperTokens from "supertokens-auth-react";
import ThirdParty from "supertokens-auth-react/recipe/thirdparty";
import EmailPassword from "supertokens-auth-react/recipe/emailpassword";
import Session from "supertokens-auth-react/recipe/session";
SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
recipeList: [
ThirdParty.init({
onHandleEvent: async (context) => {
if (context.action === "SUCCESS") {
let { id, emails } = context.user;
if (context.isNewRecipeUser && context.user.loginMethods.length === 1) {
// TODO: Sign up
} else {
// TODO: Sign in
}
}
}
}),
EmailPassword.init({
onHandleEvent: async (context) => {
if (context.action === "SUCCESS") {
let { id, emails } = context.user;
if (context.isNewRecipeUser && context.user.loginMethods.length === 1) {
// TODO: Sign up
} else {
// TODO: Sign in
}
}
}
}),
Session.init()
]
});
info
Please refer to this page to learn more about the onHandleEvent
hook.
Important
supertokens-auth-react
SDK and will inject the React components to show the UI. Therefore, the code snippet below refers to the supertokens-auth-react
SDK.This method allows you to fire events immediately after a successful sign in / up. For example to send analytics events post sign in / up.
import SuperTokens from "supertokens-auth-react";
import ThirdParty from "supertokens-auth-react/recipe/thirdparty";
import EmailPassword from "supertokens-auth-react/recipe/emailpassword";
import Session from "supertokens-auth-react/recipe/session";
SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
recipeList: [
ThirdParty.init({
onHandleEvent: async (context) => {
if (context.action === "SUCCESS") {
let { id, emails } = context.user;
if (context.isNewRecipeUser && context.user.loginMethods.length === 1) {
// TODO: Sign up
} else {
// TODO: Sign in
}
}
}
}),
EmailPassword.init({
onHandleEvent: async (context) => {
if (context.action === "SUCCESS") {
let { id, emails } = context.user;
if (context.isNewRecipeUser && context.user.loginMethods.length === 1) {
// TODO: Sign up
} else {
// TODO: Sign in
}
}
}
}),
Session.init()
]
});
info
Please refer to this page to learn more about the onHandleEvent
hook.
This method allows you to fire events immediately after a successful sign in / up. For example to send analytics events post sign in / up.
import SuperTokens from "supertokens-auth-react";
import ThirdParty from "supertokens-auth-react/recipe/thirdparty";
import EmailPassword from "supertokens-auth-react/recipe/emailpassword";
import Session from "supertokens-auth-react/recipe/session";
SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
recipeList: [
ThirdParty.init({
onHandleEvent: async (context) => {
if (context.action === "SUCCESS") {
let { id, emails } = context.user;
if (context.isNewRecipeUser && context.user.loginMethods.length === 1) {
// TODO: Sign up
} else {
// TODO: Sign in
}
}
}
}),
EmailPassword.init({
onHandleEvent: async (context) => {
if (context.action === "SUCCESS") {
let { id, emails } = context.user;
if (context.isNewRecipeUser && context.user.loginMethods.length === 1) {
// TODO: Sign up
} else {
// TODO: Sign in
}
}
}
}),
Session.init()
]
});
info
Please refer to this page to learn more about the onHandleEvent
hook.
#
2) On the backend#
Sign in / sign up overrideFor this, you'll have to override the following recipe functions in the init
function call, on the backend:
emailPassword signUp
: Sign up with email & passwordemailPassword signIn
: Sign in with email & passwordthirdParty signInUp
: Sign in or up with third party
- NodeJS
- GoLang
- Python
- Other Frameworks
Important
import SuperTokens from "supertokens-node";
import ThirdParty from "supertokens-node/recipe/thirdparty"
import EmailPassword from "supertokens-node/recipe/emailpassword"
import Session from "supertokens-node/recipe/session";
SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
supertokens: {
connectionURI: "...",
},
recipeList: [
ThirdParty.init({
override: {
functions: (originalImplementation) => {
return {
...originalImplementation,
// override the thirdparty sign in / up function
signInUp: async function (input) {
// TODO: Some pre sign in / up logic
let response = await originalImplementation.signInUp(input);
if (response.status === "OK") {
let accessToken = response.oAuthTokens["access_token"];
let firstName = response.rawUserInfoFromProvider.fromUserInfoAPI!["first_name"];
if (input.session === undefined) {
if (response.createdNewRecipeUser && response.user.loginMethods.length === 1) {
// TODO: some post sign up logic
} else {
// TODO: some post sign in logic
}
}
}
return response;
}
}
}
}
}),
EmailPassword.init({
override: {
functions: (originalImplementation) => {
return {
...originalImplementation,
// override the email password sign up function
signUp: async function (input) {
// TODO: some pre sign up logic
let response = await originalImplementation.signUp(input);
if (response.status === "OK" && response.user.loginMethods.length === 1 && input.session === undefined) {
// TODO: some post sign up logic
}
return response;
},
// override the email password sign in function
signIn: async function (input) {
// TODO: some pre sign in logic
let response = await originalImplementation.signIn(input);
if (response.status === "OK" && input.session === undefined) {
// TODO: some post sign in logic
}
return response;
},
}
}
}
}),
Session.init({ /* ... */ })
]
});
import (
"fmt"
"github.com/supertokens/supertokens-golang/recipe/emailpassword"
"github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels"
"github.com/supertokens/supertokens-golang/recipe/thirdparty"
"github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels"
"github.com/supertokens/supertokens-golang/supertokens"
)
func main() {
supertokens.Init(supertokens.TypeInput{
RecipeList: []supertokens.Recipe{
emailpassword.Init(&epmodels.TypeInput{
Override: &epmodels.OverrideStruct{
Functions: func(originalImplementation epmodels.RecipeInterface) epmodels.RecipeInterface {
// create a copy of the originalImplementation
originalEmailPasswordSignUp := *originalImplementation.SignUp
originalEmailPasswordSignIn := *originalImplementation.SignIn
// override the email password sign up function
(*originalImplementation.SignUp) = func(email, password string, tenantId string, userContext supertokens.UserContext) (epmodels.SignUpResponse, error) {
// TODO: some pre sign up logic
resp, err := originalEmailPasswordSignUp(email, password, tenantId, userContext)
if err != nil {
return epmodels.SignUpResponse{}, err
}
if resp.OK != nil {
// TODO: some post sign up logic
}
return resp, err
}
// override the email password sign in function
(*originalImplementation.SignIn) = func(email, password string, tenantId string, userContext supertokens.UserContext) (epmodels.SignInResponse, error) {
// TODO: some pre sign in logic
resp, err := originalEmailPasswordSignIn(email, password, tenantId, userContext)
if err != nil {
return epmodels.SignInResponse{}, err
}
if resp.OK != nil {
// TODO: some post sign in logic
}
return resp, err
}
return originalImplementation
},
},
}),
thirdparty.Init(&tpmodels.TypeInput{
Override: &tpmodels.OverrideStruct{
Functions: func(originalImplementation tpmodels.RecipeInterface) tpmodels.RecipeInterface {
// create a copy of the originalImplementation
originalThirdPartySignInUp := *originalImplementation.SignInUp
// override the thirdparty sign in / up function
(*originalImplementation.SignInUp) = func(thirdPartyID, thirdPartyUserID, email string, oAuthTokens tpmodels.TypeOAuthTokens, rawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider, tenantId string, userContext supertokens.UserContext) (tpmodels.SignInUpResponse, error) {
// TODO: some pre sign in / up logic
resp, err := originalThirdPartySignInUp(thirdPartyID, thirdPartyUserID, email, oAuthTokens, rawUserInfoFromProvider, tenantId, userContext)
if err != nil {
return tpmodels.SignInUpResponse{}, err
}
if resp.OK != nil {
user := resp.OK.User
fmt.Println(user)
accessToken := resp.OK.OAuthTokens["access_token"].(string)
firstName := resp.OK.RawUserInfoFromProvider.FromUserInfoAPI["first_name"].(string)
fmt.Println(accessToken)
fmt.Println(firstName)
if resp.OK.CreatedNewUser {
// TODO: Post sign up logic
} else {
// TODO: Post sign in logic
}
}
return resp, err
}
return originalImplementation
},
},
}),
},
})
}
from supertokens_python import init, InputAppInfo
from supertokens_python.recipe import thirdparty, emailpassword, session
from supertokens_python.recipe.thirdparty.interfaces import RecipeInterface as ThirdPartyRecipeInterface
from supertokens_python.recipe.emailpassword.interfaces import RecipeInterface as EmailPasswordRecipeInterface, SignInOkResult, SignUpOkResult
from supertokens_python.recipe.thirdparty.types import RawUserInfoFromProvider
from typing import Dict, Any
def override_thirdparty_functions(original_implementation: ThirdPartyRecipeInterface) -> ThirdPartyRecipeInterface:
original_thirdparty_sign_in_up = original_implementation.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]
):
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:
print("New user was created")
# TODO: Post sign up logic
else:
print("User already existed and was signed in")
# TODO: Post sign in logic
return result
original_implementation.sign_in_up = thirdparty_sign_in_up
return original_implementation
def override_emailpassword_functions(original_implementation: EmailPasswordRecipeInterface) -> EmailPasswordRecipeInterface:
original_emailpassword_sign_up = original_implementation.sign_up
original_emailpassword_sign_in = original_implementation.sign_in
async def emailpassword_sign_up(
email: str,
password: str,
tenant_id: str,
user_context: Dict[str, Any]
):
# TODO: some pre sign up logic
result = await original_emailpassword_sign_up(email, password, tenant_id, user_context)
if isinstance(result, SignUpOkResult):
# TODO: some post sign up logic
pass
return result
async def emailpassword_sign_in(
email: str,
password: str,
tenant_id: str,
user_context: Dict[str, Any]
):
# TODO: some pre sign in logic
result = await original_emailpassword_sign_in(email, password, tenant_id, user_context)
if isinstance(result, SignInOkResult):
# TODO: some post sign in logic
pass
return result
original_implementation.sign_up = emailpassword_sign_up
original_implementation.sign_in = emailpassword_sign_in
return original_implementation
init(
app_info=InputAppInfo(api_domain="...", app_name="...", website_domain="..."),
framework='...',
recipe_list=[
thirdparty.init(
override=thirdparty.InputOverrideConfig(
functions=override_thirdparty_functions
),
),
emailpassword.init(
override=emailpassword.InputOverrideConfig(
functions=override_emailpassword_functions
),
),
session.init(),
]
)
Using the code above, if createdNewUser
is true
or in emailPassword signUpPOST
, you can (for example):
- Add the user's ID and their info to your own database (in addition to it being stored in SuperTokens).
- Send analytics events about a sign up.
- Send a welcome email to the user.
- You can associate a role to the user.
#
Accessing custom form fields during email password sign upDuring email password sign up, if you would like to access the custom form fields that you may have added, you can do so by overriding the emailPassword signUpPOST
API:
- NodeJS
- GoLang
- Python
- Other Frameworks
Important
import SuperTokens from "supertokens-node";
import EmailPassword from "supertokens-node/recipe/emailpassword";
import Session from "supertokens-node/recipe/session";
// backend
SuperTokens.init({
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
supertokens: {
connectionURI: "...",
},
recipeList: [
EmailPassword.init({
override: {
apis: (originalImplementation) => {
return {
...originalImplementation,
signUpPOST: async function (input) {
// First we call the original implementation of signUpPOST.
let response = await originalImplementation.signUpPOST!(input);
// Post sign up response, we check if it was successful
if (response.status === "OK" && response.user.loginMethods.length === 1 && input.session === undefined) {
let { id, emails } = response.user;
// TODO: sign up successful
// here we fetch a custom form field for the user's name.
// Note that for this to be available, you need to define
// this custom form field.
let name = ""
for (let i = 0; i < input.formFields.length; i++) {
if (input.formFields[i].id == "name") {
name = input.formFields[i].value
}
}
// Use name..
}
return response;
}
}
},
functions: (originalImplementation) => {
return {
...originalImplementation,
// TODO: from previous code snippets
}
}
}
}),
Session.init({ /* ... */ })
]
});
import (
"fmt"
"github.com/supertokens/supertokens-golang/recipe/emailpassword"
"github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels"
"github.com/supertokens/supertokens-golang/supertokens"
)
func main() {
supertokens.Init(supertokens.TypeInput{
RecipeList: []supertokens.Recipe{
emailpassword.Init(&epmodels.TypeInput{
Override: &epmodels.OverrideStruct{
APIs: func(originalImplementation epmodels.APIInterface) epmodels.APIInterface {
originalEmailPasswordSignUpPOST := *originalImplementation.SignUpPOST
(*originalImplementation.SignUpPOST) = func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.SignUpPOSTResponse, error) {
// pre API logic...
resp, err := originalEmailPasswordSignUpPOST(formFields, tenantId, options, userContext)
if err != nil {
return epmodels.SignUpPOSTResponse{}, err
}
if resp.OK != nil {
userId := resp.OK.User.ID
fmt.Println(userId)
// sign up successful
// here we fetch a custom form field for the user's name.
// Note that for this to be available, you need to define
// this custom form field.
name := ""
for _, field := range formFields {
if field.ID == "name" {
name = field.Value
}
}
fmt.Println(name)
}
return resp, nil
}
return originalImplementation
},
Functions: func(originalImplementation epmodels.RecipeInterface) epmodels.RecipeInterface {
// TODO: From previous code snippet...
return originalImplementation
},
},
}),
},
})
}
from supertokens_python import init, InputAppInfo
from supertokens_python.recipe import emailpassword
from supertokens_python.recipe.emailpassword.interfaces import APIInterface, APIOptions, SignUpPostOkResult, RecipeInterface
from typing import Dict, Any, List
from supertokens_python.recipe.emailpassword.types import FormField
def override_emailpassword_apis(original_implementation: APIInterface):
original_emailpassword_sign_up_post = original_implementation.sign_up_post
async def emailpassword_sign_up_post(
form_fields: List[FormField],
tenant_id: str,
api_options: APIOptions,
user_context: Dict[str, Any]
):
# call the default behaviour as show below
result = await original_emailpassword_sign_up_post(form_fields, tenant_id, api_options, user_context)
if isinstance(result, SignUpPostOkResult):
# TODO: sign up successful
# here we fetch a custom form field for the user's name.
# Note that for this to be available, you need to define
# this custom form field.
# loop result formfields
name = ""
for form_field in form_fields:
if form_field.id == "name":
name = form_field.value
break
print(name)
return result
original_implementation.sign_up_post = emailpassword_sign_up_post
return original_implementation
def override_thirdpartyemailpassword_functions(original_implementation: RecipeInterface):
# TODO: from previous code snippets
return original_implementation
init(
app_info=InputAppInfo(api_domain="...", app_name="...", website_domain="..."),
framework='...',
recipe_list=[
emailpassword.init(
override=emailpassword.InputOverrideConfig(
apis=override_emailpassword_apis
)
)
]
)
#
API override vs Functions overrideFor most purposes, you should be using Functions override. Functions override logic is called whenever the API is called from the frontend as well as if you call the sign up / sign in functions yourself manually via the SDK (like emailpassword.signIn(...)
).
For example, when the frontend calls the email password sign up API, the SDK invokes the API.signUpPOST
above. When you call the original implementation of this function, that function calls the Functions.signUp
function first, and if that's successful, it calls the Session recipe's createNewSession
function.
Therefore, if you want to associate a role with a user, you would want to do that in the Functions.signUp
function since then those roles would get added to the session in the subsequent call to the Session.createNewSession
function. If instead, you associate a role to the user in the API.signUpPOST
(after calling the original implementation), the role will not be automatically added to the session since the Session.createNewSession
would have already been called before the original implementation returns.
The only time it makes sense to override the API functions is if you want to access an argument that's not available in the recipe function. For example, the custom form fields for email password sign up is an input to the API.signUpPOST
, but not to the Functions.signUp
, so if you want to access the form fields, you should override the API.signUpPOST
as shown above. You can also always add the formFields to the userContext object and read it later in the Functions.signUp
override, but then you would lose the typing of the form field array structure (which is not a runtime problem, but just a slightly bad developer experience).