Security Bundle API¶
flask_unchained.bundles.security
The Security Bundle. |
flask_unchained.bundles.security.config
Config options for the Security Bundle. |
|
Config options for logging in and out. |
|
Config options for token authentication. |
|
Config options for user registration |
|
Config options for changing passwords |
|
Config options for recovering forgotten passwords |
|
Config options for encryption hashing. |
flask_unchained.bundles.security.extensions
The Security extension. |
flask_unchained.bundles.security.views
The controller for the security bundle. |
|
RESTful API resource for the |
flask_unchained.bundles.security.decorators
Decorator for requiring an authenticated user, optionally with roles. |
|
Decorator for requiring an authenticated user to be the same as the user in the URL parameters. |
|
Decorator requiring that there is no user currently logged in. |
flask_unchained.bundles.security.models
Base user model. |
|
Base role model. |
|
flask_unchained.bundles.security.serializers
Marshmallow serializer for the |
|
Marshmallow serializer for the |
flask_unchained.bundles.security.services
The security service. |
|
The security utils service. |
|
|
|
|
flask_unchained.bundles.security.forms
The default login form. |
|
The default register form. |
|
The default change password form. |
|
The default forgot password form. |
|
The default reset password form. |
|
The default resend confirmation email form. |
SecurityBundle¶
-
class
flask_unchained.bundles.security.SecurityBundle[source]¶ The Security Bundle. Integrates Flask Login and Flask Principal with Flask Unchained.
-
name: str = 'security_bundle'¶ The name of the Security Bundle.
-
command_group_names= ['users', 'roles']¶ Click groups for the Security Bundle.
-
Config¶
Config options for the Security Bundle. |
|
Config options for logging in and out. |
|
Config options for token authentication. |
|
Config options for user registration |
|
Config options for changing passwords |
|
Config options for recovering forgotten passwords |
|
Config options for encryption hashing. |
General¶
-
class
flask_unchained.bundles.security.config.Config[source]¶ Config options for the Security Bundle.
-
SECURITY_ANONYMOUS_USER¶ alias of
flask_unchained.bundles.security.models.anonymous_user.AnonymousUser
-
SECURITY_UNAUTHORIZED_CALLBACK()¶ This callback gets called when authorization fails. By default we abort with an HTTP status code of 401 (UNAUTHORIZED).
-
SECURITY_DATETIME_FACTORY()¶ Factory function to use when creating new dates. By default we use
datetime.now(timezone.utc)to create a timezone-aware datetime.
-
Authentication¶
-
class
flask_unchained.bundles.security.config.AuthenticationConfig[source]¶ Config options for logging in and out.
-
SECURITY_LOGIN_FORM¶
-
SECURITY_DEFAULT_REMEMBER_ME= False¶ Whether or not the login form should default to checking the “Remember me?” option.
-
SECURITY_REMEMBER_SALT= 'security-remember-salt'¶ Salt used for the remember me cookie token.
-
SECURITY_USER_IDENTITY_ATTRIBUTES= ['email']¶ List of attributes on the user model that can used for logging in with. Each must be unique.
-
SECURITY_POST_LOGIN_REDIRECT_ENDPOINT= '/'¶ The endpoint or url to redirect to after a successful login.
-
SECURITY_POST_LOGOUT_REDIRECT_ENDPOINT= '/'¶ The endpoint or url to redirect to after a user logs out.
-
Token Authentication¶
-
class
flask_unchained.bundles.security.config.TokenConfig[source]¶ Config options for token authentication.
-
SECURITY_TOKEN_AUTHENTICATION_KEY= 'auth_token'¶ Specifies the query string parameter to read when using token authentication.
-
SECURITY_TOKEN_AUTHENTICATION_HEADER= 'Authentication-Token'¶ Specifies the HTTP header to read when using token authentication.
-
SECURITY_TOKEN_MAX_AGE= None¶ Specifies the number of seconds before an authentication token expires. Defaults to None, meaning the token never expires.
-
Registration¶
-
class
flask_unchained.bundles.security.config.RegistrationConfig[source]¶ Config options for user registration
-
SECURITY_REGISTERABLE= False¶ Whether or not to enable registration.
-
SECURITY_REGISTER_FORM¶ alias of
flask_unchained.bundles.security.forms.RegisterForm
-
SECURITY_POST_REGISTER_REDIRECT_ENDPOINT= None¶ The endpoint or url to redirect to after a user completes the registration form.
-
SECURITY_SEND_REGISTER_EMAIL= False¶ Whether or not send a welcome email after a user completes the registration form.
-
SECURITY_CONFIRMABLE= False¶ Whether or not to enable required email confirmation for new users.
-
SECURITY_SEND_CONFIRMATION_FORM¶ alias of
flask_unchained.bundles.security.forms.SendConfirmationForm
-
SECURITY_CONFIRM_SALT= 'security-confirm-salt'¶ Salt used for the confirmation token.
-
SECURITY_LOGIN_WITHOUT_CONFIRMATION= False¶ Allow users to login without confirming their email first. (This option only applies when
SECURITY_CONFIRMABLEis True.)
-
SECURITY_CONFIRM_EMAIL_WITHIN= '5 days'¶ How long to wait until considering the token in confirmation emails to be expired.
-
SECURITY_POST_CONFIRM_REDIRECT_ENDPOINT= None¶ Endpoint or url to redirect to after the user confirms their email. Defaults to
SECURITY_POST_LOGIN_REDIRECT_ENDPOINT.
-
SECURITY_CONFIRM_ERROR_REDIRECT_ENDPOINT= None¶ Endpoint to redirect to if there’s an error confirming the user’s email.
-
Change Password¶
-
class
flask_unchained.bundles.security.config.ChangePasswordConfig[source]¶ Config options for changing passwords
-
SECURITY_CHANGEABLE= False¶ Whether or not to enable change password functionality.
-
SECURITY_CHANGE_PASSWORD_FORM¶ alias of
flask_unchained.bundles.security.forms.ChangePasswordForm
-
SECURITY_POST_CHANGE_REDIRECT_ENDPOINT= None¶ Endpoint or url to redirect to after the user changes their password.
-
SECURITY_SEND_PASSWORD_CHANGED_EMAIL= False¶ Whether or not to send the user an email when their password has been changed. Defaults to True, and it’s strongly recommended to leave this option enabled.
-
Forgot Password¶
-
class
flask_unchained.bundles.security.config.ForgotPasswordConfig[source]¶ Config options for recovering forgotten passwords
-
SECURITY_RECOVERABLE= False¶ Whether or not to enable forgot password functionality.
-
SECURITY_FORGOT_PASSWORD_FORM¶ alias of
flask_unchained.bundles.security.forms.ForgotPasswordForm
-
SECURITY_RESET_PASSWORD_FORM¶ alias of
flask_unchained.bundles.security.forms.ResetPasswordForm
-
SECURITY_RESET_SALT= 'security-reset-salt'¶ Salt used for the reset token.
-
SECURITY_RESET_PASSWORD_WITHIN= '5 days'¶ Specifies the amount of time a user has before their password reset link expires. Always pluralized the time unit for this value. Defaults to 5 days.
-
SECURITY_POST_RESET_REDIRECT_ENDPOINT= None¶ Endpoint or url to redirect to after the user resets their password.
-
SECURITY_INVALID_RESET_TOKEN_REDIRECT= 'security_controller.forgot_password'¶ Endpoint or url to redirect to if the reset token is invalid.
-
SECURITY_EXPIRED_RESET_TOKEN_REDIRECT= 'security_controller.forgot_password'¶ Endpoint or url to redirect to if the reset token is expired.
-
SECURITY_API_RESET_PASSWORD_HTTP_GET_REDIRECT= None¶ Endpoint or url to redirect to if a GET request is made to the reset password view. Defaults to None, meaning no redirect. Useful for single page apps.
-
SECURITY_SEND_PASSWORD_RESET_NOTICE_EMAIL= False¶ Whether or not to send the user an email when their password has been reset. Defaults to True, and it’s strongly recommended to leave this option enabled.
-
Encryption¶
-
class
flask_unchained.bundles.security.config.EncryptionConfig[source]¶ Config options for encryption hashing.
-
SECURITY_PASSWORD_SALT= 'security-password-salt'¶ Specifies the HMAC salt. This is only used if the password hash type is set to something other than plain text.
-
SECURITY_PASSWORD_HASH= 'bcrypt'¶ Specifies the password hash algorithm to use when hashing passwords. Recommended values for production systems are
argon2,bcrypt, orpbkdf2_sha512. May require extra packages to be installed.
-
SECURITY_PASSWORD_SINGLE_HASH= False¶ Specifies that passwords should only be hashed once. By default, passwords are hashed twice, first with SECURITY_PASSWORD_SALT, and then with a random salt. May be useful for integrating with other applications.
-
SECURITY_PASSWORD_SCHEMES= ['argon2', 'bcrypt', 'pbkdf2_sha512', 'plaintext']¶ List of algorithms that can be used for hashing passwords.
-
SECURITY_PASSWORD_HASH_OPTIONS= {}¶ Specifies additional options to be passed to the hashing method.
-
SECURITY_DEPRECATED_PASSWORD_SCHEMES= ['auto']¶ List of deprecated algorithms for hashing passwords.
-
SECURITY_HASHING_SCHEMES= ['sha512_crypt']¶ List of algorithms that can be used for creating and validating tokens.
-
SECURITY_DEPRECATED_HASHING_SCHEMES= []¶ List of deprecated algorithms for creating and validating tokens.
-
The Security Extension¶
-
class
flask_unchained.bundles.security.Security[source]¶ The Security extension:
from flask_unchained.bundles.security import security
-
context_processor(fn)[source]¶ Add a context processor that runs for every view with a template in the security bundle.
- Parameters
fn – A function that returns a dictionary of template context variables.
-
forgot_password_context_processor(fn)[source]¶ Add a context processor for the
SecurityController.forgot_password()view.- Parameters
fn – A function that returns a dictionary of template context variables.
-
login_context_processor(fn)[source]¶ Add a context processor for the
SecurityController.login()view.- Parameters
fn – A function that returns a dictionary of template context variables.
-
register_context_processor(fn)[source]¶ Add a context processor for the
SecurityController.register()view.- Parameters
fn – A function that returns a dictionary of template context variables.
-
reset_password_context_processor(fn)[source]¶ Add a context processor for the
SecurityController.reset_password()view.- Parameters
fn – A function that returns a dictionary of template context variables.
-
change_password_context_processor(fn)[source]¶ Add a context processor for the
SecurityController.change_password()view.- Parameters
fn – A function that returns a dictionary of template context variables.
-
send_confirmation_context_processor(fn)[source]¶ Add a context processor for the
SecurityController.send_confirmation_email()view.- Parameters
fn – A function that returns a dictionary of template context variables.
-
Views¶
Decorators¶
-
flask_unchained.bundles.security.auth_required(decorated_fn=None, **role_rules)[source]¶ Decorator for requiring an authenticated user, optionally with roles.
Roles are passed as keyword arguments, like so:
@auth_required(role='REQUIRE_THIS_ONE_ROLE') @auth_required(roles=['REQUIRE', 'ALL', 'OF', 'THESE', 'ROLES']) @auth_required(one_of=['EITHER_THIS_ROLE', 'OR_THIS_ONE'])
Either of the role or roles kwargs can also be combined with one_of:
@auth_required(role='REQUIRED', one_of=['THIS', 'OR_THIS'])
Aborts with
HTTP 401: Unauthorizedif no user is logged in, orHTTP 403: Forbiddenif any of the specified role checks fail.
-
flask_unchained.bundles.security.auth_required_same_user(*args, **kwargs)[source]¶ Decorator for requiring an authenticated user to be the same as the user in the URL parameters. By default the user url parameter name to lookup is
id, but this can be customized by passing an argument:@auth_require_same_user('user_id') @bp.route('/users/<int:user_id>/foo/<int:id>') def get(user_id, id): # do stuff
Any keyword arguments are passed along to the @auth_required decorator, so roles can also be specified in the same was as it, eg:
@auth_required_same_user('user_id', role='ROLE_ADMIN')
Aborts with
HTTP 403: Forbiddenif the user-check fails.
SecurityController¶
-
class
flask_unchained.bundles.security.SecurityController[source]¶ The controller for the security bundle.
-
check_auth_token(**kwargs)[source]¶ View function to check a token, and if it’s valid, log the user in.
Disabled by default; must be explicitly enabled in your
routes.py.
-
send_confirmation_email()[source]¶ View function which sends confirmation token and instructions to a user.
-
confirm_email(token)[source]¶ View function to confirm a user’s token from the confirmation email send to them. Supports html and json requests.
-
forgot_password()[source]¶ View function to request a password recovery email with a reset token. Supports html and json requests.
-
UserResource¶
Models and Managers¶
User¶
-
class
flask_unchained.bundles.security.User(**kwargs)[source]¶ Base user model. Includes
email,password,is_active, andconfirmed_atcolumns, and a many-to-many relationship to theRolemodel via the intermediaryUserRolejoin table.
UserManager¶
-
class
flask_unchained.bundles.security.UserManager[source]¶ ModelManagerfor theUsermodel.
Role¶
RoleManager¶
-
class
flask_unchained.bundles.security.RoleManager[source]¶ ModelManagerfor theRolemodel.
UserRole¶
Serializers¶
UserSerializer¶
RoleSerializer¶
Services¶
SecurityService¶
-
class
flask_unchained.bundles.security.SecurityService(mail: Optional[flask_unchained.bundles.mail.extensions.mail.Mail] = None)[source]¶ The security service.
Contains shared business logic that doesn’t belong in controllers, but isn’t so low level that it belongs in
SecurityUtilsService.-
login_user(user: flask_unchained.bundles.security.models.user.User, remember: Optional[bool] = None, duration: Optional[datetime.timedelta] = None, force: bool = False, fresh: bool = True) → bool[source]¶ Logs a user in. You should pass the actual user object to this. If the user’s is_active property is
False, they will not be logged in unless force isTrue.This will return
Trueif the log in attempt succeeds, andFalseif it fails (i.e. because the user is inactive).- Parameters
user (object) – The user object to log in.
remember (bool) – Whether to remember the user after their session expires. Defaults to
False.duration (
datetime.timedelta) – The amount of time before the remember cookie expires. IfNonethe value set in the settings is used. Defaults toNone.force (bool) – If the user is inactive, setting this to
Truewill log them in regardless. Defaults toFalse.fresh (bool) – setting this to
Falsewill log in the user with a session marked as not “fresh”. Defaults toTrue.
-
logout_user()[source]¶ Logs out the current user and cleans up the remember me cookie (if any).
Sends signal identity_changed (from flask_principal). Sends signal user_logged_out (from flask_login).
-
register_user(user, allow_login=None, send_email=None, _force_login_without_confirmation=False)[source]¶ Service method to register a user.
Sends signal user_registered.
Returns True if the user has been logged in, False otherwise.
-
change_password(user, password, send_email=None)[source]¶ Service method to change a user’s password.
Sends signal password_changed.
- Parameters
user – The
User’s password to change.password – The new password.
send_email – Whether or not to override the config option
SECURITY_SEND_PASSWORD_CHANGED_EMAILand force either sending or not sending an email.
-
reset_password(user, password)[source]¶ Service method to reset a user’s password. The same as
change_password()except we this method sends a different notification email.Sends signal password_reset.
- Parameters
user –
password –
- Returns
-
send_email_confirmation_instructions(user)[source]¶ Sends the confirmation instructions email for the specified user.
Sends signal confirm_instructions_sent.
- Parameters
user – The user to send the instructions to.
-
send_reset_password_instructions(user)[source]¶ Sends the reset password instructions email for the specified user.
Sends signal reset_password_instructions_sent.
- Parameters
user – The user to send the instructions to.
-
SecurityUtilsService¶
-
class
flask_unchained.bundles.security.SecurityUtilsService[source]¶ The security utils service. Mainly contains lower-level encryption/token handling code.
-
get_hmac(password)[source]¶ Returns a Base64 encoded HMAC+SHA512 of the password signed with the salt specified by
SECURITY_PASSWORD_SALT.- Parameters
password – The password to sign.
-
verify_password(user, password)[source]¶ Returns
Trueif the password is valid for the specified user.Additionally, the hashed password in the database is updated if the hashing algorithm happens to have changed.
- Parameters
user – The user to verify against
password – The plaintext password to verify
-
hash_password(password)[source]¶ Hash the specified plaintext password.
It uses the configured hashing options.
- Parameters
password – The plaintext password to hash
-
verify_hash(hashed_data, compare_data)[source]¶ Verify a hash in the security token hashing context.
-
use_double_hash(password_hash=None)[source]¶ Return a bool indicating whether a password should be hashed twice.
-
generate_confirmation_token(user)[source]¶ Generates a unique confirmation token for the specified user.
- Parameters
user – The user to work with
-
confirm_email_token_status(token)[source]¶ Returns the expired status, invalid status, and user of a confirmation token. For example:
expired, invalid, user = confirm_email_token_status('...')
- Parameters
token – The confirmation token
-
generate_reset_password_token(user)[source]¶ Generates a unique reset password token for the specified user.
- Parameters
user – The user to work with
-
reset_password_token_status(token)[source]¶ Returns the expired status, invalid status, and user of a password reset token. For example:
expired, invalid, user, data = reset_password_token_status('...')
- Parameters
token – The password reset token
-
get_token_status(token, serializer, max_age=None, return_data=False)[source]¶ Get the status of a token.
- Parameters
token – The token to check
serializer – The name of the serializer. Can be one of the following:
confirm,login,resetmax_age – The name of the max age config option. Can be one of the following:
SECURITY_CONFIRM_EMAIL_WITHINorSECURITY_RESET_PASSWORD_WITHIN
-
Forms¶
LoginForm¶
-
class
flask_unchained.bundles.security.forms.LoginForm(*args, **kwargs)[source]¶ The default login form.
-
validate()[source]¶ Validate the form by calling
validateon each field. ReturnsTrueif validation passes.If the form defines a
validate_<fieldname>method, it is appended as an extra validator for the field’svalidate.- Parameters
extra_validators – A dict mapping field names to lists of extra validator methods to run. Extra validators run after validators passed when creating the field. If the form has
validate_<fieldname>, it is the last extra validator.
-
RegisterForm¶
ChangePasswordForm¶
-
class
flask_unchained.bundles.security.forms.ChangePasswordForm(*args, **kwargs)[source]¶ The default change password form.
-
validate()[source]¶ Validate the form by calling
validateon each field. ReturnsTrueif validation passes.If the form defines a
validate_<fieldname>method, it is appended as an extra validator for the field’svalidate.- Parameters
extra_validators – A dict mapping field names to lists of extra validator methods to run. Extra validators run after validators passed when creating the field. If the form has
validate_<fieldname>, it is the last extra validator.
-
ForgotPasswordForm¶
ResetPasswordForm¶
SendConfirmationForm¶
-
class
flask_unchained.bundles.security.forms.SendConfirmationForm(*args, **kwargs)[source]¶ The default resend confirmation email form.
-
validate()[source]¶ Validate the form by calling
validateon each field. ReturnsTrueif validation passes.If the form defines a
validate_<fieldname>method, it is appended as an extra validator for the field’svalidate.- Parameters
extra_validators – A dict mapping field names to lists of extra validator methods to run. Extra validators run after validators passed when creating the field. If the form has
validate_<fieldname>, it is the last extra validator.
-
Validators¶
-
flask_unchained.bundles.security.forms.password_equal(form, field)¶ Compares the values of two fields.
- Parameters
fieldname – The name of the other field to compare to.
message – Error message to raise in case of a validation error. Can be interpolated with %(other_label)s and %(other_name)s to provide a more helpful error.
-
flask_unchained.bundles.security.forms.new_password_equal(form, field)¶ Compares the values of two fields.
- Parameters
fieldname – The name of the other field to compare to.
message – Error message to raise in case of a validation error. Can be interpolated with %(other_label)s and %(other_name)s to provide a more helpful error.