Security Bundle API

flask_unchained.bundles.security

SecurityBundle

The Security Bundle.

flask_unchained.bundles.security.config

Config

Config options for the Security Bundle.

AuthenticationConfig

Config options for logging in and out.

TokenConfig

Config options for token authentication.

RegistrationConfig

Config options for user registration

ChangePasswordConfig

Config options for changing passwords

ForgotPasswordConfig

Config options for recovering forgotten passwords

EncryptionConfig

Config options for encryption hashing.

flask_unchained.bundles.security.extensions

Security

The Security extension.

flask_unchained.bundles.security.views

SecurityController

The controller for the security bundle.

UserResource

RESTful API resource for the User model.

flask_unchained.bundles.security.decorators

auth_required

Decorator for requiring an authenticated user, optionally with roles.

auth_required_same_user

Decorator for requiring an authenticated user to be the same as the user in the URL parameters.

anonymous_user_required

Decorator requiring that there is no user currently logged in.

flask_unchained.bundles.security.models

User

Base user model.

Role

Base role model.

UserRole

Join table between the User and Role models.

flask_unchained.bundles.security.serializers

UserSerializer

Marshmallow serializer for the User model.

RoleSerializer

Marshmallow serializer for the Role model.

flask_unchained.bundles.security.services

SecurityService

The security service.

SecurityUtilsService

The security utils service.

UserManager

ModelManager for the User model.

RoleManager

ModelManager for the Role model.

flask_unchained.bundles.security.forms

LoginForm

The default login form.

RegisterForm

The default register form.

ChangePasswordForm

The default change password form.

ForgotPasswordForm

The default forgot password form.

ResetPasswordForm

The default reset password form.

SendConfirmationForm

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

Config options for the Security Bundle.

AuthenticationConfig

Config options for logging in and out.

TokenConfig

Config options for token authentication.

RegistrationConfig

Config options for user registration

ChangePasswordConfig

Config options for changing passwords

ForgotPasswordConfig

Config options for recovering forgotten passwords

EncryptionConfig

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

alias of flask_unchained.bundles.security.forms.LoginForm

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_CONFIRMABLE is 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, or pbkdf2_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.

mail_context_processor(fn)[source]

Add a context processor to be used when rendering all the email templates.

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: Unauthorized if no user is logged in, or HTTP 403: Forbidden if 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: Forbidden if the user-check fails.

flask_unchained.bundles.security.anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None)[source]

Decorator requiring that there is no user currently logged in.

Aborts with HTTP 403: Forbidden if there is an authenticated user.

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.

login()[source]

View function to log a user in. Supports html and json requests.

logout()[source]

View function to log a user out. Supports html and json requests.

register()[source]

View function to register user. Supports html and json requests.

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.

reset_password(token)[source]

View function verify a users reset password token from the email we sent to them. It also handles the form for them to set a new password. Supports html and json requests.

change_password(**kwargs)[source]

View function for a user to change their password. Supports html and json requests.

UserResource

class flask_unchained.bundles.security.UserResource[source]

RESTful API resource for the User model.

create(user, errors)[source]

Create an instance of a model.

Parameters
  • instance – The created model instance.

  • errors – Any errors.

Returns

The created model instance, or a dictionary of errors.

Models and Managers

User

class flask_unchained.bundles.security.User(**kwargs)[source]

Base user model. Includes email, password, is_active, and confirmed_at columns, and a many-to-many relationship to the Role model via the intermediary UserRole join table.

get_auth_token(security_utils_service='INJECTABLE_PARAMETER')[source]

Returns the user’s authentication token.

has_role(role)[source]

Returns True if the user identifies with the specified role.

Parameters

role – A role name or Role instance

UserManager

class flask_unchained.bundles.security.UserManager[source]

ModelManager for the User model.

Role

class flask_unchained.bundles.security.Role(**kwargs)[source]

Base role model. Includes an name column and a many-to-many relationship with the User model via the intermediary UserRole join table.

RoleManager

class flask_unchained.bundles.security.RoleManager[source]

ModelManager for the Role model.

UserRole

class flask_unchained.bundles.security.UserRole(user=None, role=None, **kwargs)[source]

Join table between the User and Role models.

Serializers

UserSerializer

class flask_unchained.bundles.security.serializers.UserSerializer[source]

Marshmallow serializer for the User model.

RoleSerializer

class flask_unchained.bundles.security.serializers.RoleSerializer(*args, **kwargs)[source]

Marshmallow serializer for the Role model.

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 is True.

This will return True if the log in attempt succeeds, and False if 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. If None the value set in the settings is used. Defaults to None.

  • force (bool) – If the user is inactive, setting this to True will log them in regardless. Defaults to False.

  • fresh (bool) – setting this to False will log in the user with a session marked as not “fresh”. Defaults to True.

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_EMAIL and 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.

confirm_user(user)[source]

Confirms the specified user. Returns False if the user has already been confirmed, True otherwise.

Parameters

user – The user to confirm.

send_mail(subject, to, template, **template_ctx)[source]

Utility method to send mail with the mail template context.

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.

get_auth_token(user)[source]

Returns the user’s authentication token.

verify_password(user, password)[source]

Returns True if 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

hash_data(data)[source]

Hash data in the security token hashing context.

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, reset

  • max_age – The name of the max age config option. Can be one of the following: SECURITY_CONFIRM_EMAIL_WITHIN or SECURITY_RESET_PASSWORD_WITHIN

get_within_delta(key)[source]

Get a timedelta object from the application configuration following the internal convention of:

<Amount of Units> <Type of Units>

Examples of valid config values:

5 days
10 minutes
Parameters

key – The config value key

Forms

LoginForm

class flask_unchained.bundles.security.forms.LoginForm(*args, **kwargs)[source]

The default login form.

validate()[source]

Validate the form by calling validate on each field. Returns True if validation passes.

If the form defines a validate_<fieldname> method, it is appended as an extra validator for the field’s validate.

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

class flask_unchained.bundles.security.forms.RegisterForm(*args, **kwargs)[source]

The default register form.

ChangePasswordForm

class flask_unchained.bundles.security.forms.ChangePasswordForm(*args, **kwargs)[source]

The default change password form.

validate()[source]

Validate the form by calling validate on each field. Returns True if validation passes.

If the form defines a validate_<fieldname> method, it is appended as an extra validator for the field’s validate.

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

class flask_unchained.bundles.security.forms.ForgotPasswordForm(*args, **kwargs)[source]

The default forgot password form.

ResetPasswordForm

class flask_unchained.bundles.security.forms.ResetPasswordForm(*args, **kwargs)[source]

The default reset password form.

SendConfirmationForm

class flask_unchained.bundles.security.forms.SendConfirmationForm(*args, **kwargs)[source]

The default resend confirmation email form.

validate()[source]

Validate the form by calling validate on each field. Returns True if validation passes.

If the form defines a validate_<fieldname> method, it is appended as an extra validator for the field’s validate.

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.

flask_unchained.bundles.security.forms.unique_user_email(form, field)[source]
flask_unchained.bundles.security.forms.valid_user_email(form, field)[source]