Module supertokens_python.recipe.emailpassword
Expand source code
# Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.
#
# This software is licensed under the Apache License, Version 2.0 (the
# "License") as published by the Apache Software Foundation.
#
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import annotations
from typing import TYPE_CHECKING, Union
from supertokens_python.ingredients.emaildelivery.types import (
EmailDeliveryConfig,
EmailDeliveryInterface,
)
from supertokens_python.recipe.emailpassword.types import EmailTemplateVars
from .emaildelivery.services import SMTPService
from .recipe import EmailPasswordRecipe
from .utils import (
EmailPasswordOverrideConfig,
InputFormField,
InputOverrideConfig,
InputSignUpFeature,
)
if TYPE_CHECKING:
from supertokens_python.supertokens import RecipeInit
def init(
sign_up_feature: Union[InputSignUpFeature, None] = None,
override: Union[EmailPasswordOverrideConfig, None] = None,
email_delivery: Union[EmailDeliveryConfig[EmailTemplateVars], None] = None,
) -> RecipeInit:
return EmailPasswordRecipe.init(
sign_up_feature,
override,
email_delivery,
)
__all__ = [
"EmailDeliveryConfig",
"EmailDeliveryInterface",
"EmailPasswordOverrideConfig",
"EmailPasswordRecipe",
"EmailTemplateVars",
"InputFormField",
"InputOverrideConfig", # deprecated, use EmailPasswordOverrideConfig instead
"InputSignUpFeature",
"SMTPService",
"init",
]
Sub-modules
supertokens_python.recipe.emailpassword.apisupertokens_python.recipe.emailpassword.asynciosupertokens_python.recipe.emailpassword.constantssupertokens_python.recipe.emailpassword.emaildeliverysupertokens_python.recipe.emailpassword.exceptionssupertokens_python.recipe.emailpassword.interfacessupertokens_python.recipe.emailpassword.recipesupertokens_python.recipe.emailpassword.recipe_implementationsupertokens_python.recipe.emailpassword.synciosupertokens_python.recipe.emailpassword.typessupertokens_python.recipe.emailpassword.utils
Functions
def init(sign_up_feature: Union[InputSignUpFeature, None] = None, override: Union[BaseOverrideConfig[RecipeInterface, APIInterface], None] = None, email_delivery: Union[EmailDeliveryConfig[PasswordResetEmailTemplateVars], None] = None)
Classes
class EmailPasswordOverrideConfig (**data: Any)-
Base class for input override config with API overrides.
Create a new model by parsing and validating input data from keyword arguments.
Raises [
ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.selfis explicitly positional-only to allowselfas a field name.Ancestors
- BaseOverrideConfig
- BaseOverrideConfigWithoutAPI
- CamelCaseBaseModel
- APIResponse
- abc.ABC
- pydantic.main.BaseModel
- typing.Generic
Class variables
var model_config-
The type of the None singleton.
class InputOverrideConfig (**data: Any)-
Base class for input override config with API overrides.
Create a new model by parsing and validating input data from keyword arguments.
Raises [
ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.selfis explicitly positional-only to allowselfas a field name.Ancestors
- BaseOverrideConfig
- BaseOverrideConfigWithoutAPI
- CamelCaseBaseModel
- APIResponse
- abc.ABC
- pydantic.main.BaseModel
- typing.Generic
Inherited members
class EmailDeliveryConfig (service: Union[EmailDeliveryInterface[_T], None] = None, override: Union[Callable[[EmailDeliveryInterface[_T]], EmailDeliveryInterface[_T]], None] = None)-
Helper class that provides a standard way to create an ABC using inheritance.
Expand source code
class EmailDeliveryConfig(ABC, Generic[_T]): def __init__( self, service: Union[EmailDeliveryInterface[_T], None] = None, override: Union[ Callable[[EmailDeliveryInterface[_T]], EmailDeliveryInterface[_T]], None ] = None, ) -> None: self.service = service self.override = overrideAncestors
- abc.ABC
- typing.Generic
class EmailDeliveryInterface-
Helper class that provides a standard way to create an ABC using inheritance.
Expand source code
class EmailDeliveryInterface(ABC, Generic[_T]): @abstractmethod async def send_email(self, template_vars: _T, user_context: Dict[str, Any]) -> None: passAncestors
- abc.ABC
- typing.Generic
Subclasses
- BackwardCompatibilityService
- SMTPService
- BackwardCompatibilityService
- SMTPService
- BackwardCompatibilityService
- SMTPService
- BackwardCompatibilityService
- SMTPService
Methods
async def send_email(self, template_vars: _T, user_context: Dict[str, Any]) ‑> None
class EmailPasswordRecipe (recipe_id: str, app_info: AppInfo, ingredients: EmailPasswordIngredients, config: EmailPasswordConfig)-
Helper class that provides a standard way to create an ABC using inheritance.
Expand source code
class EmailPasswordRecipe(RecipeModule): recipe_id = "emailpassword" __instance = None email_delivery: EmailDeliveryIngredient[EmailTemplateVars] def __init__( self, recipe_id: str, app_info: AppInfo, ingredients: EmailPasswordIngredients, config: EmailPasswordConfig, ): super().__init__(recipe_id, app_info) self.config = validate_and_normalise_user_input( app_info, config=config, ) recipe_implementation = RecipeImplementation( Querier.get_instance(recipe_id), self.config ) self.recipe_implementation = self.config.override.functions( recipe_implementation ) email_delivery_ingredient = ingredients.email_delivery if email_delivery_ingredient is None: self.email_delivery = EmailDeliveryIngredient( self.config.get_email_delivery_config(self.recipe_implementation) ) else: self.email_delivery = email_delivery_ingredient api_implementation = APIImplementation() self.api_implementation = self.config.override.apis(api_implementation) def callback(): mfa_instance = MultiFactorAuthRecipe.get_instance() if mfa_instance is not None: async def f1(_: TenantConfig): return ["emailpassword"] mfa_instance.add_func_to_get_all_available_secondary_factor_ids_from_other_recipes( GetAllAvailableSecondaryFactorIdsFromOtherRecipesFunc(f1) ) async def get_factors_setup_for_user( user: User, _: Dict[str, Any] ) -> List[str]: for login_method in user.login_methods: # We don't check for tenant_id here because if we find the user # with emailpassword login_method from different tenant, then # we assume the factor is setup for this user. And as part of factor # completion, we associate that login_method with the session's tenant_id if login_method.recipe_id == EmailPasswordRecipe.recipe_id: return ["emailpassword"] return [] mfa_instance.add_func_to_get_factors_setup_for_user_from_other_recipes( GetFactorsSetupForUserFromOtherRecipesFunc( get_factors_setup_for_user ) ) async def get_emails_for_factor( user: User, session_recipe_user_id: RecipeUserId ) -> Union[ GetEmailsForFactorOkResult, GetEmailsForFactorUnknownSessionRecipeUserIdResult, ]: # This function is called in the MFA info endpoint API. # Based on https://github.com/supertokens/supertokens-node/pull/741#discussion_r1432749346 # preparing some reusable variables for the logic below... session_login_method = next( ( lm for lm in user.login_methods if lm.recipe_user_id.get_as_string() == session_recipe_user_id.get_as_string() ), None, ) if session_login_method is None: return GetEmailsForFactorUnknownSessionRecipeUserIdResult() # We order the login methods based on time_joined (oldest first) ordered_login_methods = sorted( user.login_methods, key=lambda lm: lm.time_joined ) # Then we take the ones that belong to this recipe recipe_login_methods = [ lm for lm in ordered_login_methods if lm.recipe_id == EmailPasswordRecipe.recipe_id ] if recipe_login_methods: # If there are login methods belonging to this recipe, the factor is set up # In this case we only list email addresses that have a password associated with them result = ( # First we take the verified real emails associated with emailpassword login methods ordered by time_joined (oldest first) [ lm.email for lm in recipe_login_methods if lm.email and not is_fake_email(lm.email) and lm.verified ] + # Then we take the non-verified real emails associated with emailpassword login methods ordered by time_joined (oldest first) [ lm.email for lm in recipe_login_methods if lm.email and not is_fake_email(lm.email) and not lm.verified ] + # Lastly, fake emails associated with emailpassword login methods ordered by time_joined (oldest first) [ lm.email for lm in recipe_login_methods if lm.email and is_fake_email(lm.email) ] ) else: # This factor hasn't been set up, we list all emails belonging to the user if any( lm.email and not is_fake_email(lm.email) for lm in ordered_login_methods ): # If there is at least one real email address linked to the user, we only suggest real addresses result = [ lm.email for lm in ordered_login_methods if lm.email and not is_fake_email(lm.email) ] else: # Else we use the fake ones result = [ lm.email for lm in ordered_login_methods if lm.email and is_fake_email(lm.email) ] # Since in this case emails are not guaranteed to be unique, we de-duplicate the results, keeping the oldest one in the list. result = list(dict.fromkeys(result)) # If the login_method associated with the session has an email address, we move it to the top of the list (if it's already in the list) if ( session_login_method.email and session_login_method.email in result ): result.remove(session_login_method.email) result.insert(0, session_login_method.email) # If the list is empty we generate an email address to make the flow where the user is never asked for # an email address easier to implement. if not result: result.append( f"{session_recipe_user_id}@stfakeemail.supertokens.com" ) return GetEmailsForFactorOkResult( factor_id_to_emails_map={"emailpassword": result} ) mfa_instance.add_func_to_get_emails_for_factor_from_other_recipes( GetEmailsForFactorFromOtherRecipesFunc(get_emails_for_factor) ) mt_recipe = MultitenancyRecipe.get_instance_optional() if mt_recipe is not None: mt_recipe.all_available_first_factors.append(FactorIds.EMAILPASSWORD) PostSTInitCallbacks.add_post_init_callback(callback) def is_error_from_this_recipe_based_on_instance(self, err: Exception) -> bool: return isinstance(err, SuperTokensError) and ( isinstance(err, SuperTokensEmailPasswordError) ) def get_apis_handled(self) -> List[APIHandled]: return [ APIHandled( NormalisedURLPath(SIGNUP), "post", SIGNUP, self.api_implementation.disable_sign_up_post, ), APIHandled( NormalisedURLPath(SIGNIN), "post", SIGNIN, self.api_implementation.disable_sign_in_post, ), APIHandled( NormalisedURLPath(USER_PASSWORD_RESET_TOKEN), "post", USER_PASSWORD_RESET_TOKEN, self.api_implementation.disable_generate_password_reset_token_post, ), APIHandled( NormalisedURLPath(USER_PASSWORD_RESET), "post", USER_PASSWORD_RESET, self.api_implementation.disable_password_reset_post, ), APIHandled( NormalisedURLPath(SIGNUP_EMAIL_EXISTS_OLD), "get", SIGNUP_EMAIL_EXISTS_OLD, self.api_implementation.disable_email_exists_get, ), APIHandled( NormalisedURLPath(SIGNUP_EMAIL_EXISTS), "get", SIGNUP_EMAIL_EXISTS, self.api_implementation.disable_email_exists_get, ), ] async def handle_api_request( self, request_id: str, tenant_id: str, request: BaseRequest, path: NormalisedURLPath, method: str, response: BaseResponse, user_context: Dict[str, Any], ): api_options = APIOptions( request, response, self.recipe_id, self.config, self.recipe_implementation, self.get_app_info(), self.email_delivery, ) if request_id == SIGNUP: return await handle_sign_up_api( tenant_id, self.api_implementation, api_options, user_context ) if request_id == SIGNIN: return await handle_sign_in_api( tenant_id, self.api_implementation, api_options, user_context ) if request_id in (SIGNUP_EMAIL_EXISTS, SIGNUP_EMAIL_EXISTS_OLD): return await handle_email_exists_api( tenant_id, self.api_implementation, api_options, user_context ) if request_id == USER_PASSWORD_RESET_TOKEN: return await handle_generate_password_reset_token_api( tenant_id, self.api_implementation, api_options, user_context ) if request_id == USER_PASSWORD_RESET: return await handle_password_reset_api( tenant_id, self.api_implementation, api_options, user_context ) return None async def handle_error( self, request: BaseRequest, err: SuperTokensError, response: BaseResponse, user_context: Dict[str, Any], ) -> BaseResponse: if isinstance(err, SuperTokensEmailPasswordError): if isinstance(err, FieldError): response.set_json_content( {"status": "FIELD_ERROR", "formFields": err.get_json_form_fields()} ) return response raise err def get_all_cors_headers(self) -> List[str]: return [] @staticmethod def init( sign_up_feature: Optional[InputSignUpFeature] = None, override: Optional[EmailPasswordOverrideConfig] = None, email_delivery: Optional[EmailDeliveryConfig[EmailTemplateVars]] = None, ): from supertokens_python.plugins import OverrideMap, apply_plugins config = EmailPasswordConfig( sign_up_feature=sign_up_feature, email_delivery=email_delivery, override=override, ) def func(app_info: AppInfo, plugins: List[OverrideMap]): if EmailPasswordRecipe.__instance is None: ingredients = EmailPasswordIngredients(None) EmailPasswordRecipe.__instance = EmailPasswordRecipe( recipe_id=EmailPasswordRecipe.recipe_id, app_info=app_info, ingredients=ingredients, config=apply_plugins( recipe_id=EmailPasswordRecipe.recipe_id, config=config, plugins=plugins, ), ) return EmailPasswordRecipe.__instance raise Exception( None, "Emailpassword recipe has already been initialised. Please check your code for bugs.", ) return func @staticmethod def get_instance() -> EmailPasswordRecipe: if EmailPasswordRecipe.__instance is not None: return EmailPasswordRecipe.__instance raise_general_exception( "Initialisation not done. Did you forget to call the SuperTokens.init function?" ) @staticmethod def reset(): if ("SUPERTOKENS_ENV" not in environ) or ( environ["SUPERTOKENS_ENV"] != "testing" ): raise_general_exception("calling testing function in non testing env") EmailPasswordRecipe.__instance = NoneAncestors
- RecipeModule
- abc.ABC
Class variables
var email_delivery : EmailDeliveryIngredient[PasswordResetEmailTemplateVars]-
The type of the None singleton.
var recipe_id-
The type of the None singleton.
Static methods
def get_instance() ‑> EmailPasswordRecipedef init(sign_up_feature: Optional[InputSignUpFeature] = None, override: Optional[BaseOverrideConfig[RecipeInterface, APIInterface]] = None, email_delivery: Optional[EmailDeliveryConfig[PasswordResetEmailTemplateVars]] = None)def reset()
Methods
def get_all_cors_headers(self) ‑> List[str]def get_apis_handled(self) ‑> List[APIHandled]async def handle_api_request(self, request_id: str, tenant_id: str, request: BaseRequest, path: NormalisedURLPath, method: str, response: BaseResponse, user_context: Dict[str, Any])async def handle_error(self, request: BaseRequest, err: SuperTokensError, response: BaseResponse, user_context: Dict[str, Any])def is_error_from_this_recipe_based_on_instance(self, err: Exception) ‑> bool
Inherited members
class InputFormField (id: str, validate: Union[Callable[[str, str], Awaitable[Union[str, None]]], None] = None, optional: Union[bool, None] = None)-
Expand source code
class InputFormField: def __init__( self, id: str, # pylint: disable=redefined-builtin validate: Union[ Callable[[str, str], Awaitable[Union[str, None]]], None, ] = None, optional: Union[bool, None] = None, ): self.id = id self.validate = validate self.optional = optional class InputSignUpFeature (form_fields: Union[List[InputFormField], None] = None)-
Expand source code
class InputSignUpFeature: def __init__(self, form_fields: Union[List[InputFormField], None] = None): if form_fields is None: form_fields = [] self.form_fields = normalise_sign_up_form_fields(form_fields) class EmailTemplateVars (user: PasswordResetEmailTemplateVarsUser, password_reset_link: str, tenant_id: str)-
Expand source code
class PasswordResetEmailTemplateVars: def __init__( self, user: PasswordResetEmailTemplateVarsUser, password_reset_link: str, tenant_id: str, ) -> None: self.user = user self.password_reset_link = password_reset_link self.tenant_id = tenant_id def to_json(self) -> Dict[str, Any]: return { "type": "PASSWORD_RESET", "user": self.user.to_json(), "passwordResetLink": self.password_reset_link, "tenantId": self.tenant_id, }Methods
def to_json(self) ‑> Dict[str, Any]
class SMTPService (smtp_settings: SMTPSettings, override: Optional[Callable[[SMTPServiceInterface[PasswordResetEmailTemplateVars]], SMTPServiceInterface[PasswordResetEmailTemplateVars]]] = None)-
Helper class that provides a standard way to create an ABC using inheritance.
Expand source code
class SMTPService(EmailDeliveryInterface[EmailTemplateVars]): service_implementation: SMTPServiceInterface[EmailTemplateVars] def __init__( self, smtp_settings: SMTPSettings, override: Union[Callable[[SMTPOverrideInput], SMTPOverrideInput], None] = None, ) -> None: transporter = Transporter(smtp_settings) oi = ServiceImplementation(transporter) self.service_implementation = oi if override is None else override(oi) async def send_email( self, template_vars: EmailTemplateVars, user_context: Dict[str, Any], ) -> None: content = await self.service_implementation.get_content( template_vars, user_context ) await self.service_implementation.send_raw_email(content, user_context)Ancestors
- EmailDeliveryInterface
- abc.ABC
- typing.Generic
Class variables
var service_implementation : SMTPServiceInterface[PasswordResetEmailTemplateVars]-
The type of the None singleton.
Methods
async def send_email(self, template_vars: PasswordResetEmailTemplateVars, user_context: Dict[str, Any]) ‑> None