API¶
The external (json/form) API is described here
Core¶
- class flask_security.Security(app=None, datastore=None, register_blueprint=True, **kwargs)¶
The
Security
class initializes the Flask-Security extension.- Parameters:
app – The application.
datastore – An instance of a user datastore.
register_blueprint – to register the Security blueprint or not.
login_form – set form for the login view
verify_form – set form for re-authentication due to freshness check
register_form – set form for the register view when SECURITY_CONFIRMABLE is false
confirm_register_form – set form for the register view when SECURITY_CONFIRMABLE is true
forgot_password_form – set form for the forgot password view
reset_password_form – set form for the reset password view
change_password_form – set form for the change password view
send_confirmation_form – set form for the send confirmation view
passwordless_login_form – set form for the passwordless login view
two_factor_setup_form – set form for the 2FA setup view
two_factor_verify_code_form – set form the the 2FA verify code view
two_factor_rescue_form – set form for the 2FA rescue view
us_signin_form – set form for the unified sign in view
us_setup_form – set form for the unified sign in setup view
us_setup_validate_form – set form for the unified sign in setup validate view
us_verify_form – set form for re-authenticating due to freshness check
anonymous_user – class to use for anonymous user
render_template – function to use to render templates. The default is Flask’s render_template() function.
json_encoder_cls – Class to use as blueprint.json_encoder. Defaults to
FsJsonEncoder
totp_cls – Class to use as TOTP factory. Defaults to
Totp
phone_util_cls – Class to use for phone number utilities. Defaults to
PhoneUtil
mail_util_cls – Class to use for sending emails. Defaults to
MailUtil
password_util_cls – Class to use for password normalization/validation. Defaults to
PasswordUtil
New in version 3.4.0:
verify_form
added as part of freshness/re-authenticationNew in version 3.4.0:
us_signin_form
,us_setup_form
,us_setup_validate_form
, andus_verify_form
added as part of the Unified Sign In feature.New in version 3.4.0:
totp_cls
added to enable applications to implement replay protection - seeTotp
.New in version 3.4.0:
phone_util_cls
added to allow different phone number parsing implementations - seePhoneUtil
New in version 4.0.0:
mail_util_cls
added to isolate mailing handling.password_util_cls
added to encapsulate password validation/normalization.Deprecated since version 4.0.0:
send_mail
andsend_mail_task
. Replaced withmail_util_cls
.two_factor_verify_password_form
removed.password_validator
removed in favor of the newpassword_util_cls
.- init_app(app, datastore=None, register_blueprint=None, **kwargs)¶
Initializes the Flask-Security extension for the specified application and datastore implementation.
- Parameters:
app – The application.
datastore – An instance of a user datastore.
register_blueprint – to register the Security blueprint or not.
- reauthn_handler(cb)¶
Callback when endpoint required a fresh authentication. This is called by
auth_required()
.- Parameters:
cb –
Callback function with signature (within, grace)
- within:
timedelta that endpoint required fresh authentication within.
- grace:
timedelta of grace period that endpoint allowed.
Should return a Response or something Flask can create a Response from. Can raise an exception if it is handled as part of
flask.errorhandler(<exception>)
The default implementation will return a 401 response if the request was JSON, otherwise will redirect to
SECURITY_US_VERIFY_URL
(ifSECURITY_UNIFIED_SIGNIN
is enabled) else toSECURITY_VERIFY_URL
. If both of those are None it sends anabort(401)
.See
flask_security.auth_required()
for details about freshness checking.New in version 3.4.0.
- render_json(cb)¶
Callback to render response payload as JSON.
- Parameters:
cb –
Callback function with signature (payload, code, headers=None, user=None)
- payload:
A dict. Please see the formal API spec for details.
- code:
Http status code
- headers:
Headers object
- user:
the UserDatastore object (or None). Note that this is usually the same as current_user - but not always.
The default implementation simply returns:
headers["Content-Type"] = "application/json" payload = dict(meta=dict(code=code), response=payload) return make_response(jsonify(payload), code, headers)
Important
Be aware the Flask’s
jsonify
method will first look to see if ajson_encoder
has been set on the blueprint corresponding to the current request. If not then it looks for ajson_encoder
registered on the app; and finally uses Flask’s default JSONEncoder class. Flask-Security registersFsJsonEncoder()
as its blueprint json_encoder.This can be used by applications to unify all their JSON API responses. This is called in a request context and should return a Response or something Flask can create a Response from.
New in version 3.3.0.
- unauthn_handler(cb)¶
Callback for failed authentication. This is called by
auth_required()
,auth_token_required()
orhttp_auth_required()
if authentication fails.- Parameters:
cb –
Callback function with signature (mechanisms, headers=None)
- mechanisms:
List of which authentication mechanisms were tried
- headers:
dict of headers to return
Should return a Response or something Flask can create a Response from. Can raise an exception if it is handled as part of
flask.errorhandler(<exception>)
The default implementation will return a 401 response if the request was JSON, otherwise lets
flask_login.login_manager.unauthorized()
handle redirects.New in version 3.3.0.
- unauthz_handler(cb)¶
Callback for failed authorization. This is called by the
roles_required()
,roles_accepted()
,permissions_required()
, orpermissions_accepted()
if a role or permission is missing.- Parameters:
cb –
Callback function with signature (func, params)
- func:
the decorator function (e.g. roles_required)
- params:
list of what (if any) was passed to the decorator.
Should return a Response or something Flask can create a Response from. Can raise an exception if it is handled as part of flask.errorhandler(<exception>)
With the passed parameters the application could deliver a concise error message.
New in version 3.3.0.
- want_json(fn)¶
Function that returns True if response should be JSON (based on the request)
- Parameters:
fn –
Function with the following signature (request)
- request:
Werkzueg/Flask request
The default implementation returns True if either the Content-Type is “application/json” or the best Accept header value is “application/json”.
New in version 3.3.0.
- flask_security.current_user¶
A proxy for the current user.
- flask_security.Security.unauthorized_handler()¶
If an endpoint fails authentication or authorization from one of the decorators described below (except
login_required
), a method annotated with this decorator will be called. Forlogin_required
(which is implemented in Flask-Login) use flask_security.login_manager.unauthorized_handlerDeprecated since version 3.3.0.
Protecting Views¶
- flask_security.anonymous_user_required(f)¶
Decorator which requires that caller NOT be logged in. If a logged in user accesses an endpoint protected with this decorator they will be redirected to the SECURITY_POST_LOGIN_VIEW. If the caller requests a JSON response, a 400 will be returned.
Changed in version 3.3.0: Support for JSON response was added.
- flask_security.http_auth_required(realm)¶
Decorator that protects endpoints using Basic HTTP authentication.
- Parameters:
realm – optional realm name
If authentication fails, then a 401 with the ‘WWW-Authenticate’ header set will be returned.
Once authenticated, if so configured, CSRF protection will be tested.
- flask_security.auth_token_required(fn)¶
Decorator that protects endpoints using token authentication. The token should be added to the request by the client by using a query string variable with a name equal to the configuration value of SECURITY_TOKEN_AUTHENTICATION_KEY or in a request header named that of the configuration value of SECURITY_TOKEN_AUTHENTICATION_HEADER
Once authenticated, if so configured, CSRF protection will be tested.
- flask_security.auth_required(*auth_methods, **kwargs)¶
Decorator that protects endpoints through multiple mechanisms Example:
@app.route('/dashboard') @auth_required('token', 'session') def dashboard(): return 'Dashboard'
- Parameters:
auth_methods – Specified mechanisms (token, basic, session). If not specified then all current available mechanisms (except “basic”) will be tried. A callable can also be passed (useful if you need app/request context). The callable must return a list.
within –
Add ‘freshness’ check to authentication. Is either an int specifying # of minutes, or a callable that returns a timedelta. For timedeltas, timedelta.total_seconds() is used for the calculations:
If > 0, then the caller must have authenticated within the time specified (as measured using the session cookie).
If 0 and not within the grace period (see below) the caller will always be redirected to re-authenticate.
If < 0 (the default) no freshness check is performed.
Note that Basic Auth, by definition, is always ‘fresh’ and will never result in a redirect/error.
grace – Add a grace period for freshness checks. As above, either an int or a callable returning a timedelta. If not specified then
SECURITY_FRESHNESS_GRACE_PERIOD
is used. The grace period allows callers to complete the required operations w/o being prompted again. Seeflask_security.check_and_update_authn_fresh()
for details.
Note that regardless of order specified - they will be tried in the following order: token, session, basic.
The first mechanism that succeeds is used, following that, depending on configuration, CSRF protection will be tested.
On authentication failure .Security.unauthorized_callback (deprecated) or
Security.unauthn_handler()
will be called.- As a side effect, upon successful authentication, the request global
fs_authn_via
will be set to the method (“basic”, “token”, “session”)
Note
If “basic” is specified in addition to other methods, then if authentication fails, a 401 with the “WWW-Authenticate” header will be returned - rather than being redirected to the login view.
Changed in version 3.3.0: If
auth_methods
isn’t specified, then all will be tried. Authentication mechanisms will always be tried in order oftoken
,session
,basic
regardless of how they are specified in theauth_methods
parameter.Changed in version 3.4.0: Added
within
andgrace
parameters to enforce a freshness check.Changed in version 3.4.4: If
auth_methods
isn’t specified try all mechanisms EXCEPTbasic
.Changed in version 4.0.0: auth_methods can be passed as a callable.
- flask_security.login_required(func)¶
If you decorate a view with this, it will ensure that the current user is logged in and authenticated before calling the actual view. (If they are not, it calls the
LoginManager.unauthorized
callback.) For example:@app.route('/post') @login_required def post(): pass
If there are only certain times you need to require that your user is logged in, you can do so with:
if not current_user.is_authenticated: return current_app.login_manager.unauthorized()
…which is essentially the code that this function adds to your views.
It can be convenient to globally turn off authentication when unit testing. To enable this, if the application configuration variable LOGIN_DISABLED is set to True, this decorator will be ignored.
Note
Per W3 guidelines for CORS preflight requests, HTTP
OPTIONS
requests are exempt from login checks.- Parameters:
func (function) – The view function to decorate.
- flask_security.roles_required(*roles)¶
Decorator which specifies that a user must have all the specified roles. Example:
@app.route('/dashboard') @roles_required('admin', 'editor') def dashboard(): return 'Dashboard'
The current user must have both the admin role and editor role in order to view the page.
- Parameters:
roles – The required roles.
- flask_security.roles_accepted(*roles)¶
Decorator which specifies that a user must have at least one of the specified roles. Example:
@app.route('/create_post') @roles_accepted('editor', 'author') def create_post(): return 'Create Post'
The current user must have either the editor role or author role in order to view the page.
- Parameters:
roles – The possible roles.
- flask_security.permissions_required(*fsperms)¶
Decorator which specifies that a user must have all the specified permissions. Example:
@app.route('/dashboard') @permissions_required('admin-write', 'editor-write') def dashboard(): return 'Dashboard'
The current user must have BOTH permissions (via the roles it has) to view the page.
N.B. Don’t confuse these permissions with flask-principle Permission()!
- Parameters:
fsperms – The required permissions.
New in version 3.3.0.
- flask_security.permissions_accepted(*fsperms)¶
Decorator which specifies that a user must have at least one of the specified permissions. Example:
@app.route('/create_post') @permissions_accepted('editor-write', 'author-wrote') def create_post(): return 'Create Post'
The current user must have one of the permissions (via the roles it has) to view the page.
N.B. Don’t confuse these permissions with flask-principle Permission()!
- Parameters:
fsperms – The possible permissions.
New in version 3.3.0.
- flask_security.unauth_csrf(fall_through=False)¶
Decorator for endpoints that don’t need authentication but do want CSRF checks (available via Header rather than just form). This is required when setting WTF_CSRF_CHECK_DEFAULT = False since in that case, without this decorator, the form validation will attempt to do the CSRF check, and that will fail since the csrf-token is in the header (for pure JSON requests).
This decorator does nothing unless Flask-WTF::CSRFProtect has been initialized.
This decorator does nothing if WTF_CSRF_ENABLED == False.
This decorator will always require CSRF if the caller is authenticated.
This decorator will suppress CSRF if caller isn’t authenticated and has set the SECURITY_CSRF_IGNORE_UNAUTH_ENDPOINTS config variable.
- Parameters:
fall_through – if set to True, then if CSRF fails here - simply keep going. This is appropriate if underlying view is form based and once the form is instantiated, the csrf_token will be available. Note that this can mask some errors such as ‘The CSRF session token is missing.’ meaning that the caller didn’t send a session cookie and instead the caller might get a ‘The CSRF token is missing.’ error.
New in version 3.3.0.
- flask_security.handle_csrf(method)¶
Invoke CSRF protection based on authentication method.
Usually this is called as part of a decorator, but if that isn’t appropriate, endpoint code can call this directly.
If CSRF protection is appropriate, this will call flask_wtf::protect() which will raise a ValidationError on CSRF failure.
This routine does nothing if any of these are true:
WTF_CSRF_ENABLED is set to False
the Flask-WTF CSRF module hasn’t been initialized
csrfProtect already checked and accepted the token
If the passed in method is not in SECURITY_CSRF_PROTECT_MECHANISMS then not only will no CSRF code be run, but a flag in the current context
fs_ignore_csrf
will be set so that downstream code knows to ignore any CSRF checks.New in version 3.3.0.
User Object Helpers¶
- class flask_security.UserMixin¶
Mixin for User model definitions
- calc_username()¶
Come up with the best ‘username’ based on how the app is configured (via
SECURITY_USER_IDENTITY_ATTRIBUTES
). Returns the first non-null match (and converts to string). In theory this should NEVER be the empty string unless the user record isn’t actually valid.New in version 3.4.0.
- get_auth_token()¶
Constructs the user’s authentication token.
- Raises:
ValueError – If
fs_token_uniquifier
is part of model but not set.
Optionally use a separate uniquifier so that changing password doesn’t invalidate auth tokens.
This data MUST be securely signed using the
remember_token_serializer
Changed in version 4.0.0: If user model has
fs_token_uniquifier
- use that (raise ValueError if not set). Otherwise fallback to usingfs_uniqifier
.
- get_id()¶
Returns the user identification attribute. ‘Alternative-token’ for Flask-Login. This is always
fs_uniquifier
.New in version 3.4.0.
- get_redirect_qparams(existing=None)¶
Return user info that will be added to redirect query params.
- Parameters:
existing – A dict that will be updated.
- Returns:
A dict whose keys will be query params and values will be query values.
New in version 3.2.0.
Changed in version 4.0.0: Add ‘identity’ using UserMixin.calc_username() - email is optional.
- get_security_payload()¶
Serialize user object as response payload. Override this to return any/all of the user object in JSON responses. Return a dict.
- has_permission(permission)¶
Returns True if user has this permission (via a role it has).
- Parameters:
permission – permission string name
New in version 3.3.0.
- has_role(role)¶
Returns True if the user identifies with the specified role.
- Parameters:
role – A role name or Role instance
- property is_active¶
Returns True if the user is active.
- tf_send_security_token(method, **kwargs)¶
Generate and send the security code for two-factor.
- Parameters:
method – The method in which the code will be sent
kwargs – Opaque parameters that are subject to change at any time
- Returns:
None if successful, error message if not.
This is a wrapper around
tf_send_security_token()
that can be overridden to manage any errors.New in version 3.4.0.
- us_send_security_token(method, **kwargs)¶
Generate and send the security code for unified sign in.
- Parameters:
method – The method in which the code will be sent
kwargs – Opaque parameters that are subject to change at any time
- Returns:
None if successful, error message if not.
This is a wrapper around
us_send_security_token()
that can be overridden to manage any errors.New in version 3.4.0.
- verify_and_update_password(password)¶
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.
N.B. you MUST call DB commit if you are using a session-based datastore (such as SqlAlchemy) since the user instance might have been altered (i.e.
app.security.datastore.commit()
). This is usually handled in the view.- Parameters:
password – A plaintext password to verify
New in version 3.2.0.
- verify_auth_token(data)¶
Perform additional verification of contents of auth token. Prior to this being called the token has been validated (via signing) and has not expired.
- Parameters:
data – the data as formulated by
get_auth_token()
New in version 3.3.0.
Changed in version 4.0.0: If user model has
fs_token_uniquifier
- use that otherwise usefs_uniquifier
.
- class flask_security.RoleMixin¶
Mixin for Role model definitions
- add_permissions(permissions)¶
Add one or more permissions to role.
- Parameters:
permissions – a set, list, or single string.
New in version 3.3.0.
Deprecated since version 3.4.4: Use
UserDatastore.add_permissions_to_role()
- get_permissions()¶
Return set of permissions associated with role.
Supports permissions being a comma separated string, an iterable, or a set based on how the underlying DB model was built.
New in version 3.3.0.
- remove_permissions(permissions)¶
Remove one or more permissions from role.
- Parameters:
permissions – a set, list, or single string.
New in version 3.3.0.
Deprecated since version 3.4.4: Use
UserDatastore.remove_permissions_from_role()
Datastores¶
- class flask_security.UserDatastore(user_model, role_model)¶
Abstracted user datastore.
- Parameters:
user_model – A user model class definition
role_model – A role model class definition
Important
For mutating operations, the user/role will be added to the datastore (by calling self.put(<object>). If the datastore is session based (such as for SQLAlchemyDatastore) it is up to caller to actually commit the transaction by calling datastore.commit().
- activate_user(user)¶
Activates a specified user. Returns True if a change was made.
- Parameters:
user – The user to activate
- add_permissions_to_role(role, permissions)¶
Add one or more permissions to role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions added, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- add_role_to_user(user, role)¶
Adds a role to a user.
- Parameters:
user – The user to manipulate. Can be an User object or email
role – The role to add to the user. Can be a Role object or string role name
- Returns:
True is role was added, False if role already existed.
- create_role(**kwargs)¶
Creates and returns a new role from the given parameters. Supported params (depending on RoleModel):
- Parameters:
name – Role name
permissions –
a comma delimited list of permissions, a set or a list. These are user-defined strings that correspond to strings used with @permissions_required()
New in version 3.3.0.
- create_user(**kwargs)¶
Creates and returns a new user from the given parameters.
- Parameters:
email – required.
password – Hashed password.
roles – list of roles to be added to user. Can be Role objects or strings
Note
No normalization is done on email - it is assumed the caller has already done that.
Note
The roles kwparam is modified as part of the call - it will, if necessary be converted from names to role instances.
Danger
Be aware that whatever password is passed in will be stored directly in the DB. Do NOT pass in a plaintext password! Best practice is to pass in
hash_password(plaintext_password)
.Furthermore, no validation nor normalization is done on the password (e.g for minimum length).
- Best practice is::
pbad, pnorm = app.security._password_util.validate(password, True)
Look for pbad being None. Pass the normalized password pnorm to this method.
The new user’s
active
property will be set toTrue
unless explicitly set toFalse
in kwargs.
- deactivate_user(user)¶
Deactivates a specified user. Returns True if a change was made.
This will immediately disallow access to all endpoints that require authentication either via session or tokens. The user will not be able to log in again.
- Parameters:
user – The user to deactivate
- delete_user(user)¶
Deletes the specified user.
- Parameters:
user – The user to delete
- find_or_create_role(name, **kwargs)¶
Returns a role matching the given name or creates it with any additionally provided parameters.
- find_role(*args, **kwargs)¶
Returns a role matching the provided name.
- find_user(*args, **kwargs)¶
Returns a user matching the provided parameters.
- remove_permissions_from_role(role, permissions)¶
Remove one or more permissions from a role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions removed, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- remove_role_from_user(user, role)¶
Removes a role from a user.
- Parameters:
user – The user to manipulate. Can be an User object or email
role – The role to remove from the user. Can be a Role object or string role name
- Returns:
True if role was removed, False if role doesn’t exist or user didn’t have role.
- reset_user_access(user)¶
Use this method to reset user authentication methods in the case of compromise. This will:
reset fs_uniquifier - which causes session cookie, remember cookie, auth tokens to be unusable
reset fs_token_uniquifier (if present) - cause auth tokens to be unusable
remove all unified signin TOTP secrets so those can’t be used
remove all two-factor secrets so those can’t be used
Note that if using unified sign in and allow ‘email’ as a way to receive a code; if the email is compromised - login is still possible. To handle this - it is better to deactivate the user.
Note - this method isn’t used directly by Flask-Security - it is provided as a helper for an application’s administrative needs.
Remember to call commit on DB if needed.
New in version 3.4.1.
- set_token_uniquifier(user, uniquifier=None)¶
Set user’s auth token identity key. This will immediately render outstanding auth tokens invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
This method is a no-op if the user model doesn’t contain the attribute
fs_token_uniquifier
New in version 4.0.0.
- set_uniquifier(user, uniquifier=None)¶
Set user’s Flask-Security identity key. This will immediately render outstanding auth tokens, session cookies and remember cookies invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
New in version 3.3.0.
- tf_reset(user)¶
Disable two-factor auth for user
- tf_set(user, primary_method, totp_secret=None, phone=None)¶
Set two-factor info into user record. This carefully only changes things if different.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for two factor without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
- toggle_active(user)¶
Toggles a user’s active status. Always returns True.
- us_get_totp_secrets(user)¶
Return totp secrets. These are json encoded in the DB.
Returns a dict with methods as keys and secrets as values.
New in version 3.4.0.
- us_put_totp_secrets(user, secrets)¶
Save secrets. Assume to be a dict (or None) with keys as methods, and values as (encrypted) secrets.
New in version 3.4.0.
- us_reset(user)¶
Disable unified sign in for user. Be aware that if “email” is an allowed way to receive codes, they will still work (as totp secrets are generated on the fly). This will disable authenticator app and SMS.
- us_set(user, method, totp_secret=None, phone=None)¶
Set unified sign in info into user record.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for unified sign in without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
- class flask_security.SQLAlchemyUserDatastore(db, user_model, role_model)¶
A SQLAlchemy datastore implementation for Flask-Security that assumes the use of the Flask-SQLAlchemy extension.
- activate_user(user)¶
Activates a specified user. Returns True if a change was made.
- Parameters:
user – The user to activate
- add_permissions_to_role(role, permissions)¶
Add one or more permissions to role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions added, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- add_role_to_user(user, role)¶
Adds a role to a user.
- Parameters:
user – The user to manipulate. Can be an User object or email
role – The role to add to the user. Can be a Role object or string role name
- Returns:
True is role was added, False if role already existed.
- create_role(**kwargs)¶
Creates and returns a new role from the given parameters. Supported params (depending on RoleModel):
- Parameters:
name – Role name
permissions –
a comma delimited list of permissions, a set or a list. These are user-defined strings that correspond to strings used with @permissions_required()
New in version 3.3.0.
- create_user(**kwargs)¶
Creates and returns a new user from the given parameters.
- Parameters:
email – required.
password – Hashed password.
roles – list of roles to be added to user. Can be Role objects or strings
Note
No normalization is done on email - it is assumed the caller has already done that.
Note
The roles kwparam is modified as part of the call - it will, if necessary be converted from names to role instances.
Danger
Be aware that whatever password is passed in will be stored directly in the DB. Do NOT pass in a plaintext password! Best practice is to pass in
hash_password(plaintext_password)
.Furthermore, no validation nor normalization is done on the password (e.g for minimum length).
- Best practice is::
pbad, pnorm = app.security._password_util.validate(password, True)
Look for pbad being None. Pass the normalized password pnorm to this method.
The new user’s
active
property will be set toTrue
unless explicitly set toFalse
in kwargs.
- deactivate_user(user)¶
Deactivates a specified user. Returns True if a change was made.
This will immediately disallow access to all endpoints that require authentication either via session or tokens. The user will not be able to log in again.
- Parameters:
user – The user to deactivate
- delete_user(user)¶
Deletes the specified user.
- Parameters:
user – The user to delete
- find_or_create_role(name, **kwargs)¶
Returns a role matching the given name or creates it with any additionally provided parameters.
- find_role(role)¶
Returns a role matching the provided name.
- find_user(case_insensitive=False, **kwargs)¶
Returns a user matching the provided parameters.
- remove_permissions_from_role(role, permissions)¶
Remove one or more permissions from a role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions removed, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- remove_role_from_user(user, role)¶
Removes a role from a user.
- Parameters:
user – The user to manipulate. Can be an User object or email
role – The role to remove from the user. Can be a Role object or string role name
- Returns:
True if role was removed, False if role doesn’t exist or user didn’t have role.
- reset_user_access(user)¶
Use this method to reset user authentication methods in the case of compromise. This will:
reset fs_uniquifier - which causes session cookie, remember cookie, auth tokens to be unusable
reset fs_token_uniquifier (if present) - cause auth tokens to be unusable
remove all unified signin TOTP secrets so those can’t be used
remove all two-factor secrets so those can’t be used
Note that if using unified sign in and allow ‘email’ as a way to receive a code; if the email is compromised - login is still possible. To handle this - it is better to deactivate the user.
Note - this method isn’t used directly by Flask-Security - it is provided as a helper for an application’s administrative needs.
Remember to call commit on DB if needed.
New in version 3.4.1.
- set_token_uniquifier(user, uniquifier=None)¶
Set user’s auth token identity key. This will immediately render outstanding auth tokens invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
This method is a no-op if the user model doesn’t contain the attribute
fs_token_uniquifier
New in version 4.0.0.
- set_uniquifier(user, uniquifier=None)¶
Set user’s Flask-Security identity key. This will immediately render outstanding auth tokens, session cookies and remember cookies invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
New in version 3.3.0.
- tf_reset(user)¶
Disable two-factor auth for user
- tf_set(user, primary_method, totp_secret=None, phone=None)¶
Set two-factor info into user record. This carefully only changes things if different.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for two factor without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
- toggle_active(user)¶
Toggles a user’s active status. Always returns True.
- us_get_totp_secrets(user)¶
Return totp secrets. These are json encoded in the DB.
Returns a dict with methods as keys and secrets as values.
New in version 3.4.0.
- us_put_totp_secrets(user, secrets)¶
Save secrets. Assume to be a dict (or None) with keys as methods, and values as (encrypted) secrets.
New in version 3.4.0.
- us_reset(user)¶
Disable unified sign in for user. Be aware that if “email” is an allowed way to receive codes, they will still work (as totp secrets are generated on the fly). This will disable authenticator app and SMS.
- us_set(user, method, totp_secret=None, phone=None)¶
Set unified sign in info into user record.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for unified sign in without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
- class flask_security.SQLAlchemySessionUserDatastore(session, user_model, role_model)¶
A SQLAlchemy datastore implementation for Flask-Security that assumes the use of the flask_sqlalchemy_session extension.
- activate_user(user)¶
Activates a specified user. Returns True if a change was made.
- Parameters:
user – The user to activate
- add_permissions_to_role(role, permissions)¶
Add one or more permissions to role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions added, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- add_role_to_user(user, role)¶
Adds a role to a user.
- Parameters:
user – The user to manipulate. Can be an User object or email
role – The role to add to the user. Can be a Role object or string role name
- Returns:
True is role was added, False if role already existed.
- create_role(**kwargs)¶
Creates and returns a new role from the given parameters. Supported params (depending on RoleModel):
- Parameters:
name – Role name
permissions –
a comma delimited list of permissions, a set or a list. These are user-defined strings that correspond to strings used with @permissions_required()
New in version 3.3.0.
- create_user(**kwargs)¶
Creates and returns a new user from the given parameters.
- Parameters:
email – required.
password – Hashed password.
roles – list of roles to be added to user. Can be Role objects or strings
Note
No normalization is done on email - it is assumed the caller has already done that.
Note
The roles kwparam is modified as part of the call - it will, if necessary be converted from names to role instances.
Danger
Be aware that whatever password is passed in will be stored directly in the DB. Do NOT pass in a plaintext password! Best practice is to pass in
hash_password(plaintext_password)
.Furthermore, no validation nor normalization is done on the password (e.g for minimum length).
- Best practice is::
pbad, pnorm = app.security._password_util.validate(password, True)
Look for pbad being None. Pass the normalized password pnorm to this method.
The new user’s
active
property will be set toTrue
unless explicitly set toFalse
in kwargs.
- deactivate_user(user)¶
Deactivates a specified user. Returns True if a change was made.
This will immediately disallow access to all endpoints that require authentication either via session or tokens. The user will not be able to log in again.
- Parameters:
user – The user to deactivate
- delete_user(user)¶
Deletes the specified user.
- Parameters:
user – The user to delete
- find_or_create_role(name, **kwargs)¶
Returns a role matching the given name or creates it with any additionally provided parameters.
- find_role(role)¶
Returns a role matching the provided name.
- find_user(case_insensitive=False, **kwargs)¶
Returns a user matching the provided parameters.
- remove_permissions_from_role(role, permissions)¶
Remove one or more permissions from a role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions removed, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- remove_role_from_user(user, role)¶
Removes a role from a user.
- Parameters:
user – The user to manipulate. Can be an User object or email
role – The role to remove from the user. Can be a Role object or string role name
- Returns:
True if role was removed, False if role doesn’t exist or user didn’t have role.
- reset_user_access(user)¶
Use this method to reset user authentication methods in the case of compromise. This will:
reset fs_uniquifier - which causes session cookie, remember cookie, auth tokens to be unusable
reset fs_token_uniquifier (if present) - cause auth tokens to be unusable
remove all unified signin TOTP secrets so those can’t be used
remove all two-factor secrets so those can’t be used
Note that if using unified sign in and allow ‘email’ as a way to receive a code; if the email is compromised - login is still possible. To handle this - it is better to deactivate the user.
Note - this method isn’t used directly by Flask-Security - it is provided as a helper for an application’s administrative needs.
Remember to call commit on DB if needed.
New in version 3.4.1.
- set_token_uniquifier(user, uniquifier=None)¶
Set user’s auth token identity key. This will immediately render outstanding auth tokens invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
This method is a no-op if the user model doesn’t contain the attribute
fs_token_uniquifier
New in version 4.0.0.
- set_uniquifier(user, uniquifier=None)¶
Set user’s Flask-Security identity key. This will immediately render outstanding auth tokens, session cookies and remember cookies invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
New in version 3.3.0.
- tf_reset(user)¶
Disable two-factor auth for user
- tf_set(user, primary_method, totp_secret=None, phone=None)¶
Set two-factor info into user record. This carefully only changes things if different.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for two factor without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
- toggle_active(user)¶
Toggles a user’s active status. Always returns True.
- us_get_totp_secrets(user)¶
Return totp secrets. These are json encoded in the DB.
Returns a dict with methods as keys and secrets as values.
New in version 3.4.0.
- us_put_totp_secrets(user, secrets)¶
Save secrets. Assume to be a dict (or None) with keys as methods, and values as (encrypted) secrets.
New in version 3.4.0.
- us_reset(user)¶
Disable unified sign in for user. Be aware that if “email” is an allowed way to receive codes, they will still work (as totp secrets are generated on the fly). This will disable authenticator app and SMS.
- us_set(user, method, totp_secret=None, phone=None)¶
Set unified sign in info into user record.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for unified sign in without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
- class flask_security.MongoEngineUserDatastore(db, user_model, role_model)¶
A MongoEngine datastore implementation for Flask-Security that assumes the use of the Flask-MongoEngine extension.
- activate_user(user)¶
Activates a specified user. Returns True if a change was made.
- Parameters:
user – The user to activate
- add_permissions_to_role(role, permissions)¶
Add one or more permissions to role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions added, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- add_role_to_user(user, role)¶
Adds a role to a user.
- Parameters:
user – The user to manipulate. Can be an User object or email
role – The role to add to the user. Can be a Role object or string role name
- Returns:
True is role was added, False if role already existed.
- create_role(**kwargs)¶
Creates and returns a new role from the given parameters. Supported params (depending on RoleModel):
- Parameters:
name – Role name
permissions –
a comma delimited list of permissions, a set or a list. These are user-defined strings that correspond to strings used with @permissions_required()
New in version 3.3.0.
- create_user(**kwargs)¶
Creates and returns a new user from the given parameters.
- Parameters:
email – required.
password – Hashed password.
roles – list of roles to be added to user. Can be Role objects or strings
Note
No normalization is done on email - it is assumed the caller has already done that.
Note
The roles kwparam is modified as part of the call - it will, if necessary be converted from names to role instances.
Danger
Be aware that whatever password is passed in will be stored directly in the DB. Do NOT pass in a plaintext password! Best practice is to pass in
hash_password(plaintext_password)
.Furthermore, no validation nor normalization is done on the password (e.g for minimum length).
- Best practice is::
pbad, pnorm = app.security._password_util.validate(password, True)
Look for pbad being None. Pass the normalized password pnorm to this method.
The new user’s
active
property will be set toTrue
unless explicitly set toFalse
in kwargs.
- deactivate_user(user)¶
Deactivates a specified user. Returns True if a change was made.
This will immediately disallow access to all endpoints that require authentication either via session or tokens. The user will not be able to log in again.
- Parameters:
user – The user to deactivate
- delete_user(user)¶
Deletes the specified user.
- Parameters:
user – The user to delete
- find_or_create_role(name, **kwargs)¶
Returns a role matching the given name or creates it with any additionally provided parameters.
- find_role(role)¶
Returns a role matching the provided name.
- find_user(case_insensitive=False, **kwargs)¶
Returns a user matching the provided parameters.
- remove_permissions_from_role(role, permissions)¶
Remove one or more permissions from a role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions removed, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- remove_role_from_user(user, role)¶
Removes a role from a user.
- Parameters:
user – The user to manipulate. Can be an User object or email
role – The role to remove from the user. Can be a Role object or string role name
- Returns:
True if role was removed, False if role doesn’t exist or user didn’t have role.
- reset_user_access(user)¶
Use this method to reset user authentication methods in the case of compromise. This will:
reset fs_uniquifier - which causes session cookie, remember cookie, auth tokens to be unusable
reset fs_token_uniquifier (if present) - cause auth tokens to be unusable
remove all unified signin TOTP secrets so those can’t be used
remove all two-factor secrets so those can’t be used
Note that if using unified sign in and allow ‘email’ as a way to receive a code; if the email is compromised - login is still possible. To handle this - it is better to deactivate the user.
Note - this method isn’t used directly by Flask-Security - it is provided as a helper for an application’s administrative needs.
Remember to call commit on DB if needed.
New in version 3.4.1.
- set_token_uniquifier(user, uniquifier=None)¶
Set user’s auth token identity key. This will immediately render outstanding auth tokens invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
This method is a no-op if the user model doesn’t contain the attribute
fs_token_uniquifier
New in version 4.0.0.
- set_uniquifier(user, uniquifier=None)¶
Set user’s Flask-Security identity key. This will immediately render outstanding auth tokens, session cookies and remember cookies invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
New in version 3.3.0.
- tf_reset(user)¶
Disable two-factor auth for user
- tf_set(user, primary_method, totp_secret=None, phone=None)¶
Set two-factor info into user record. This carefully only changes things if different.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for two factor without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
- toggle_active(user)¶
Toggles a user’s active status. Always returns True.
- us_get_totp_secrets(user)¶
Return totp secrets. These are json encoded in the DB.
Returns a dict with methods as keys and secrets as values.
New in version 3.4.0.
- us_put_totp_secrets(user, secrets)¶
Save secrets. Assume to be a dict (or None) with keys as methods, and values as (encrypted) secrets.
New in version 3.4.0.
- us_reset(user)¶
Disable unified sign in for user. Be aware that if “email” is an allowed way to receive codes, they will still work (as totp secrets are generated on the fly). This will disable authenticator app and SMS.
- us_set(user, method, totp_secret=None, phone=None)¶
Set unified sign in info into user record.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for unified sign in without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
- class flask_security.PeeweeUserDatastore(db, user_model, role_model, role_link)¶
A PeeweeD datastore implementation for Flask-Security that assumes the use of Peewee Flask utils.
- Parameters:
user_model – A user model class definition
role_model – A role model class definition
role_link – A model implementing the many-to-many user-role relation
- activate_user(user)¶
Activates a specified user. Returns True if a change was made.
- Parameters:
user – The user to activate
- add_permissions_to_role(role, permissions)¶
Add one or more permissions to role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions added, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- add_role_to_user(user, role)¶
Adds a role to a user.
- Parameters:
user – The user to manipulate
role – The role to add to the user
- create_role(**kwargs)¶
Creates and returns a new role from the given parameters. Supported params (depending on RoleModel):
- Parameters:
name – Role name
permissions –
a comma delimited list of permissions, a set or a list. These are user-defined strings that correspond to strings used with @permissions_required()
New in version 3.3.0.
- create_user(**kwargs)¶
Creates and returns a new user from the given parameters.
- deactivate_user(user)¶
Deactivates a specified user. Returns True if a change was made.
This will immediately disallow access to all endpoints that require authentication either via session or tokens. The user will not be able to log in again.
- Parameters:
user – The user to deactivate
- delete_user(user)¶
Deletes the specified user.
- Parameters:
user – The user to delete
- find_or_create_role(name, **kwargs)¶
Returns a role matching the given name or creates it with any additionally provided parameters.
- find_role(role)¶
Returns a role matching the provided name.
- find_user(case_insensitive=False, **kwargs)¶
Returns a user matching the provided parameters.
- remove_permissions_from_role(role, permissions)¶
Remove one or more permissions from a role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions removed, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- remove_role_from_user(user, role)¶
Removes a role from a user.
- Parameters:
user – The user to manipulate
role – The role to remove from the user
- reset_user_access(user)¶
Use this method to reset user authentication methods in the case of compromise. This will:
reset fs_uniquifier - which causes session cookie, remember cookie, auth tokens to be unusable
reset fs_token_uniquifier (if present) - cause auth tokens to be unusable
remove all unified signin TOTP secrets so those can’t be used
remove all two-factor secrets so those can’t be used
Note that if using unified sign in and allow ‘email’ as a way to receive a code; if the email is compromised - login is still possible. To handle this - it is better to deactivate the user.
Note - this method isn’t used directly by Flask-Security - it is provided as a helper for an application’s administrative needs.
Remember to call commit on DB if needed.
New in version 3.4.1.
- set_token_uniquifier(user, uniquifier=None)¶
Set user’s auth token identity key. This will immediately render outstanding auth tokens invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
This method is a no-op if the user model doesn’t contain the attribute
fs_token_uniquifier
New in version 4.0.0.
- set_uniquifier(user, uniquifier=None)¶
Set user’s Flask-Security identity key. This will immediately render outstanding auth tokens, session cookies and remember cookies invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
New in version 3.3.0.
- tf_reset(user)¶
Disable two-factor auth for user
- tf_set(user, primary_method, totp_secret=None, phone=None)¶
Set two-factor info into user record. This carefully only changes things if different.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for two factor without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
- toggle_active(user)¶
Toggles a user’s active status. Always returns True.
- us_get_totp_secrets(user)¶
Return totp secrets. These are json encoded in the DB.
Returns a dict with methods as keys and secrets as values.
New in version 3.4.0.
- us_put_totp_secrets(user, secrets)¶
Save secrets. Assume to be a dict (or None) with keys as methods, and values as (encrypted) secrets.
New in version 3.4.0.
- us_reset(user)¶
Disable unified sign in for user. Be aware that if “email” is an allowed way to receive codes, they will still work (as totp secrets are generated on the fly). This will disable authenticator app and SMS.
- us_set(user, method, totp_secret=None, phone=None)¶
Set unified sign in info into user record.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for unified sign in without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
- class flask_security.PonyUserDatastore(db, user_model, role_model)¶
A Pony ORM datastore implementation for Flask-Security.
Code primarily from https://github.com/ET-CS but taken over after being abandoned.
- activate_user(user)¶
Activates a specified user. Returns True if a change was made.
- Parameters:
user – The user to activate
- add_permissions_to_role(role, permissions)¶
Add one or more permissions to role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions added, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- add_role_to_user(*args, **kwargs)¶
Adds a role to a user.
- Parameters:
user – The user to manipulate. Can be an User object or email
role – The role to add to the user. Can be a Role object or string role name
- Returns:
True is role was added, False if role already existed.
- create_role(**kwargs)¶
Creates and returns a new role from the given parameters. Supported params (depending on RoleModel):
- Parameters:
name – Role name
permissions –
a comma delimited list of permissions, a set or a list. These are user-defined strings that correspond to strings used with @permissions_required()
New in version 3.3.0.
- create_user(**kwargs)¶
Creates and returns a new user from the given parameters.
- Parameters:
email – required.
password – Hashed password.
roles – list of roles to be added to user. Can be Role objects or strings
Note
No normalization is done on email - it is assumed the caller has already done that.
Note
The roles kwparam is modified as part of the call - it will, if necessary be converted from names to role instances.
Danger
Be aware that whatever password is passed in will be stored directly in the DB. Do NOT pass in a plaintext password! Best practice is to pass in
hash_password(plaintext_password)
.Furthermore, no validation nor normalization is done on the password (e.g for minimum length).
- Best practice is::
pbad, pnorm = app.security._password_util.validate(password, True)
Look for pbad being None. Pass the normalized password pnorm to this method.
The new user’s
active
property will be set toTrue
unless explicitly set toFalse
in kwargs.
- deactivate_user(user)¶
Deactivates a specified user. Returns True if a change was made.
This will immediately disallow access to all endpoints that require authentication either via session or tokens. The user will not be able to log in again.
- Parameters:
user – The user to deactivate
- delete_user(user)¶
Deletes the specified user.
- Parameters:
user – The user to delete
- find_or_create_role(name, **kwargs)¶
Returns a role matching the given name or creates it with any additionally provided parameters.
- find_role(role)¶
Returns a role matching the provided name.
- find_user(case_insensitive=False, **kwargs)¶
Returns a user matching the provided parameters.
- remove_permissions_from_role(role, permissions)¶
Remove one or more permissions from a role.
- Parameters:
role – The role to modify. Can be a Role object or string role name
permissions – a set, list, or single string.
- Returns:
True if permissions removed, False if role doesn’t exist.
Caller must commit to DB.
New in version 4.0.0.
- remove_role_from_user(user, role)¶
Removes a role from a user.
- Parameters:
user – The user to manipulate. Can be an User object or email
role – The role to remove from the user. Can be a Role object or string role name
- Returns:
True if role was removed, False if role doesn’t exist or user didn’t have role.
- reset_user_access(user)¶
Use this method to reset user authentication methods in the case of compromise. This will:
reset fs_uniquifier - which causes session cookie, remember cookie, auth tokens to be unusable
reset fs_token_uniquifier (if present) - cause auth tokens to be unusable
remove all unified signin TOTP secrets so those can’t be used
remove all two-factor secrets so those can’t be used
Note that if using unified sign in and allow ‘email’ as a way to receive a code; if the email is compromised - login is still possible. To handle this - it is better to deactivate the user.
Note - this method isn’t used directly by Flask-Security - it is provided as a helper for an application’s administrative needs.
Remember to call commit on DB if needed.
New in version 3.4.1.
- set_token_uniquifier(user, uniquifier=None)¶
Set user’s auth token identity key. This will immediately render outstanding auth tokens invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
This method is a no-op if the user model doesn’t contain the attribute
fs_token_uniquifier
New in version 4.0.0.
- set_uniquifier(user, uniquifier=None)¶
Set user’s Flask-Security identity key. This will immediately render outstanding auth tokens, session cookies and remember cookies invalid.
- Parameters:
user – User to modify
uniquifier – Unique value - if none then uuid.uuid4().hex is used
New in version 3.3.0.
- tf_reset(user)¶
Disable two-factor auth for user
- tf_set(user, primary_method, totp_secret=None, phone=None)¶
Set two-factor info into user record. This carefully only changes things if different.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for two factor without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
- toggle_active(user)¶
Toggles a user’s active status. Always returns True.
- us_get_totp_secrets(user)¶
Return totp secrets. These are json encoded in the DB.
Returns a dict with methods as keys and secrets as values.
New in version 3.4.0.
- us_put_totp_secrets(user, secrets)¶
Save secrets. Assume to be a dict (or None) with keys as methods, and values as (encrypted) secrets.
New in version 3.4.0.
- us_reset(user)¶
Disable unified sign in for user. Be aware that if “email” is an allowed way to receive codes, they will still work (as totp secrets are generated on the fly). This will disable authenticator app and SMS.
- us_set(user, method, totp_secret=None, phone=None)¶
Set unified sign in info into user record.
If totp_secret isn’t provided - existing one won’t be changed. If phone isn’t provided, the existing phone number won’t be changed.
This could be called from an application to apiori setup a user for unified sign in without the user having to go through the setup process.
To get a totp_secret - use
app.security._totp_factory.generate_totp_secret()
Utils¶
- flask_security.login_user(user, remember=None, authn_via=None)¶
Perform the login routine.
If SECURITY_TRACKABLE is used, make sure you commit changes after this request (i.e.
app.security.datastore.commit()
).- Parameters:
user – The user to login
remember – Flag specifying if the remember cookie should be set. Defaults to
False
authn_via – A list of strings denoting which mechanism(s) the user authenticated with. These should be one or more of [“password”, “sms”, “authenticator”, “email”] or other ‘auto-login’ mechanisms.
- flask_security.logout_user()¶
Logs out the current user.
This will also clean up the remember me cookie if it exists.
This sends an
identity_changed
signal to note that the current identity is now the AnonymousIdentity
- flask_security.check_and_update_authn_fresh(within, grace, method=None)¶
Check if user authenticated within specified time and update grace period.
- Parameters:
within – A timedelta specifying the maximum time in the past that the caller authenticated that is still considered ‘fresh’.
grace – A timedelta that, if the current session is considered ‘fresh’ will set a grace period for which freshness won’t be checked. The intent here is that the caller shouldn’t get part-way though a set of operations and suddenly be required to authenticate again.
method – Optional - if set and == “basic” then will always return True. (since basic-auth sends username/password on every request)
If within.total_seconds() is negative, will always return True (always ‘fresh’). This effectively just disables this entire mechanism.
If “fs_gexp” is in the session and the current timestamp is less than that, return True and extend grace time (i.e. set fs_gexp to current time + grace).
If not within the grace period, and within.total_seconds() is 0, return False (not fresh).
Be aware that for this to work, sessions and therefore session cookies must be functioning and being sent as part of the request. If the required state isn’t in the session cookie then return False (not ‘fresh’).
Warning
Be sure the caller is already authenticated PRIOR to calling this method.
New in version 3.4.0.
Changed in version 4.0.0: Added method parameter.
- flask_security.get_hmac(password)¶
Returns a Base64 encoded HMAC+SHA512 of the password signed with the salt specified by SECURITY_PASSWORD_SALT.
- Parameters:
password – The password to sign
- flask_security.get_request_attr(name)¶
Retrieve a request local attribute.
Currently public attributes are:
- fs_authn_via
will be set to the authentication mechanism (session, token, basic) that the current request was authenticated with.
Returns None if attribute doesn’t exist.
New in version 4.0.0.
- flask_security.verify_password(password, password_hash)¶
Returns
True
if the password matches the supplied hash.- Parameters:
password – A plaintext password to verify
password_hash – The expected hash value of the password (usually from your database)
Note
Make sure that the password passed in has already been normalized.
- flask_security.verify_and_update_password(password, user)¶
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.
N.B. you MUST call DB commit if you are using a session-based datastore (such as SqlAlchemy) since the user instance might have been altered (i.e.
app.security.datastore.commit()
). This is usually handled in the view.- Parameters:
password – A plaintext password to verify
user – The user to verify against
Tip
This should not be called directly - rather use
UserMixin.verify_and_update_password()
- flask_security.hash_password(password)¶
Hash the specified plaintext password.
Unless the hash algorithm (as specified by SECURITY_PASSWORD_HASH) is listed in the configuration variable SECURITY_PASSWORD_SINGLE_HASH, perform a double hash - first create an HMAC from the plaintext password and the value of SECURITY_PASSWORD_SALT, then use the configured hashing algorithm. This satisfies OWASP/ASVS section 2.4.5: ‘provide additional iteration of a key derivation’.
New in version 2.0.2.
- Parameters:
password – The plaintext password to hash
- flask_security.uia_phone_mapper(identity)¶
Used to match identity as a phone number. This is a simple proxy to
PhoneUtil
See
SECURITY_USER_IDENTITY_ATTRIBUTES
.New in version 3.4.0.
- flask_security.uia_email_mapper(identity)¶
Used to match identity as an email.
See
SECURITY_USER_IDENTITY_ATTRIBUTES
.New in version 3.4.0.
- flask_security.url_for_security(endpoint, **values)¶
Return a URL for the security blueprint
- Parameters:
endpoint – the endpoint of the URL (name of the function)
values – the variable arguments of the URL rule
_external – if set to True, an absolute URL is generated. Server address can be changed via SERVER_NAME configuration variable which defaults to localhost.
_anchor – if provided this is added as anchor to the URL.
_method – if provided this explicitly specifies an HTTP method.
- flask_security.send_mail(subject, recipient, template, **context)¶
Send an email.
- Parameters:
subject – Email subject
recipient – Email recipient
template – The name of the email template
context – The context to render the template with
This formats the email and passes off to
MailUtil
to actuall send the message.
- flask_security.get_token_status(token, serializer, max_age=None, return_data=False)¶
Get the status of a token.
- Parameters:
token – The token to check
serializer – The name of the seriailzer. Can be one of the following:
confirm
,login
,reset
max_age – The name of the max age config option. Can be on of the following:
CONFIRM_EMAIL
,LOGIN
,RESET_PASSWORD
- flask_security.check_and_get_token_status(token, serializer, within=None)¶
Get the status of a token and return data.
- Parameters:
token – The token to check
serializer – The name of the serializer. Can be one of the following:
confirm
,login
,reset
,us_setup
within – max age - passed as a timedelta
- Returns:
a tuple of (expired, invalid, data)
New in version 3.4.0.
- flask_security.get_url(endpoint_or_url, qparams=None)¶
Returns a URL if a valid endpoint is found. Otherwise, returns the provided value.
- Parameters:
endpoint_or_url – The endpoint name or URL to default to
qparams – additional query params to add to end of url
- Returns:
URL
- flask_security.password_length_validator(password)¶
Test password for length.
- Parameters:
password – Plain text password to check
- Returns:
None
if password conforms to length requirements, a list of error/suggestions if not.
New in version 3.4.0.
- flask_security.password_complexity_validator(password, is_register, **kwargs)¶
Test password for complexity.
Currently just supports ‘zxcvbn’.
- Parameters:
password – Plain text password to check
is_register – if True then kwargs are arbitrary additional info. (e.g. info from a registration form). If False, must be a SINGLE key “user” that corresponds to the current_user. All string values will be extracted and sent to the complexity checker.
kwargs –
- Returns:
None
if password is complex enough, a list of error/suggestions if not. Be aware that zxcvbn does not (easily) provide a way to localize messages.
New in version 3.4.0.
- flask_security.password_breached_validator(password)¶
Check if password on breached list. Does nothing unless
SECURITY_PASSWORD_CHECK_BREACHED
is set. If password is found on the breached list, return an error if the count is greater than or equal toSECURITY_PASSWORD_BREACHED_COUNT
.- Parameters:
password – Plain text password to check
- Returns:
None
if password passes breached tests, else a list of error messages.
New in version 3.4.0.
- flask_security.pwned(password)¶
Check password against pwnedpasswords API using k-Anonymity. https://haveibeenpwned.com/API/v3
- Returns:
Count of password in DB (0 means hasn’t been compromised) Can raise HTTPError
New in version 3.4.0.
- flask_security.transform_url(url, qparams=None, **kwargs)¶
Modify url
- Parameters:
url – url to transform (can be relative)
qparams – additional query params to add to end of url
kwargs – pieces of URL to modify - e.g. netloc=localhost:8000
- Returns:
Modified URL
New in version 3.2.0.
- flask_security.unique_identity_attribute(form, field)¶
A validator that checks the field data against all configured SECURITY_USER_IDENTITY_ATTRIBUTES. This can be used as part of registration.
Be aware that the “mapper” function likely also nornalizes the input in addition to validating it.
- Parameters:
form –
field –
- Returns:
Nothing; if field data corresponds to an existing User, ValidationError is raised.
- flask_security.us_send_security_token(user, method, totp_secret, phone_number, send_magic_link=False)¶
Generate and send the security code.
- Parameters:
user – The user to send the code to
method – The method in which the code will be sent
totp_secret – the unique shared secret of the user
phone_number – If ‘sms’ phone number to send to
send_magic_link – If true a magic link that can be clicked on will be sent. This shouldn’t be sent during a setup.
There is no return value - it is assumed that exceptions are thrown by underlying methods that callers can catch.
Flask-Security code should NOT call this directly - call
UserMixin.us_send_security_token()
New in version 3.4.0.
- flask_security.tf_send_security_token(user, method, totp_secret, phone_number)¶
Sends the security token via email/sms for the specified user.
- Parameters:
user – The user to send the code to
method – The method in which the code will be sent (‘email’ or ‘sms’, or ‘authenticator’) at the moment
totp_secret – a unique shared secret of the user
phone_number – If ‘sms’ phone number to send to
There is no return value - it is assumed that exceptions are thrown by underlying methods that callers can catch.
Flask-Security code should NOT call this directly - call
UserMixin.tf_send_security_token()
- class flask_security.FsJsonEncoder(**kwargs)¶
Flask-Security JSON encoder. Extends Flask’s JSONencoder to handle lazy-text.
New in version 3.3.0.
- class flask_security.Totp(secrets, issuer)¶
Encapsulate usage of Passlib TOTP functionality.
Flask-Security doesn’t implement any replay-attack protection out of the box as suggested by: https://passlib.readthedocs.io/en/stable/narr/totp-tutorial.html#match-verify
Subclass this and implement the get/set last_counter methods. Your subclass can be registered at Flask-Security creation/initialization time.
New in version 3.4.0.
- generate_qrcode(username, totp)¶
- Generate QRcode
Using username, totp, generate the actual QRcode image. This method can be overridden to fine-tune how the image is created - such as size, color etc.
It must return a string suitable for use in an <img src=xx> tag.
New in version 4.0.0.
- get_last_counter(user)¶
Implement this to fetch stored last_counter from cache.
- Parameters:
user – User model
- Returns:
last_counter as stored in set_last_counter()
- set_last_counter(user, tmatch)¶
Implement this to cache last_counter.
- Parameters:
user – User model
tmatch – a TotpMatch as returned from totp.verify()
- class flask_security.PhoneUtil(app)¶
Provide parsing and validation for user inputted phone numbers. Subclass this to use a different underlying phone number parsing library.
To provide your own implementation, pass in the class as
phone_util_cls
at init time. Your class will be instantiated once as part of Flask-Security initialization.New in version 3.4.0.
Changed in version 4.0.0: __init__ takes app argument, and is instantiated at Flask-Security initialization time rather than at first request.
- __init__(app)¶
Instantiate class.
- Parameters:
app – The Flask application being initialized.
- get_canonical_form(input_data)¶
Validate and return a canonical form to be stored in DB and compared against. Returns
None
if input isn’t a valid phone number.
- validate_phone_number(input_data)¶
Return
None
if a valid phone number else thePHONE_INVALID
error message.
- class flask_security.MailUtil(app)¶
Utility class providing methods for validating, normalizing and sending emails.
This default class uses the email_validator package to handle validation and normalization, and the flask_mail package to send emails.
To provide your own implementation, pass in the class as
mail_util_cls
at init time. Your class will be instantiated once as part of app initialization.New in version 4.0.0.
- __init__(app)¶
Instantiate class.
- Parameters:
app – The Flask application being initialized.
- normalize(email)¶
Given an input email - return a normalized version. Must be called in app context and uses
SECURITY_EMAIL_VALIDATOR_ARGS
config variable to pass any relevant arguments to email_validator.validate_email() method.Will throw email_validator.EmailNotValidError if email isn’t even valid.
- send_mail(template, subject, recipient, sender, body, html, user, **kwargs)¶
Send an email via the Flask-Mail extension.
- Parameters:
template – the Template name. The message has already been rendered however this might be useful to differentiate why the email is being sent.
subject – Email subject
recipient – Email recipient
sender – who to send email as (see
SECURITY_EMAIL_SENDER
)body – the rendered body (text)
html – the rendered body (html)
user – the user model
- validate(email)¶
Validate the given email. If valid, the normalized version is returned.
ValueError is thrown if not valid.
- class flask_security.PasswordUtil(app)¶
Utility class providing methods for validating and normalizing passwords.
To provide your own implementation, pass in the class as
password_util_cls
at init time. Your class will be instantiated once as part of app initialization.New in version 4.0.0.
- __init__(app)¶
Instantiate class.
- Parameters:
app – The Flask application being initialized.
- normalize(password)¶
Given an input password - return a normalized version (using Python’s unicodedata.normalize()). Must be called in app context and uses
SECURITY_PASSWORD_NORMALIZE_FORM
config variable.
- validate(password, is_register, **kwargs)¶
Password validation. Called in app/request context.
If is_register is True then kwargs will be the contents of the register form. If is_register is False, then there is a single kwarg “user” which has the current user data model.
The password is first normalized then validated. Return value is a tuple ([msgs], normalized_password)
Signals¶
See the Flask documentation on signals for information on how to use these signals in your code.
Tip
Remember to add **extra_args
to your signature so that if we add
additional parameters in the future your code doesn’t break.
See the documentation for the signals provided by the Flask-Login and Flask-Principal extensions. In addition to those signals, Flask-Security sends the following signals.
- user_authenticated¶
Sent when a user successfully authenticates. In addition to the app (which is the sender), it is passed user, and authn_via arguments. The authn_via argument specifies how the user authenticated - it will be a list with possible values of
password
,sms
,authenticator
,email
,confirm
,reset
,register
.New in version 3.4.0.
- user_registered¶
Sent when a user registers on the site. In addition to the app (which is the sender), it is passed user, confirm_token and form_data arguments. form_data is a dictionary representation of registration form’s content received with registration request.
- user_confirmed¶
Sent when a user is confirmed. In addition to the app (which is the sender), it is passed a user argument.
- confirm_instructions_sent¶
Sent when a user requests confirmation instructions. In addition to the app (which is the sender), it is passed a user argument.
- login_instructions_sent¶
Sent when passwordless login is used and user logs in. In addition to the app (which is the sender), it is passed user and login_token arguments.
- password_reset¶
Sent when a user completes a password reset. In addition to the app (which is the sender), it is passed a user argument.
- password_changed¶
Sent when a user completes a password change. In addition to the app (which is the sender), it is passed a user argument.
- reset_password_instructions_sent¶
Sent when a user requests a password reset. In addition to the app (which is the sender), it is passed user and token arguments.
- tf_code_confirmed¶
Sent when a user performs two-factor authentication login on the site. In addition to the app (which is the sender), it is passed user and method arguments.
New in version 3.3.0.
- tf_profile_changed¶
Sent when two-factor is used and user logs in. In addition to the app (which is the sender), it is passed user and method arguments.
New in version 3.3.0.
- tf_disabled¶
Sent when two-factor is disabled. In addition to the app (which is the sender), it is passed user argument.
New in version 3.3.0.
- tf_security_token_sent¶
Sent when a two factor security/access code is sent. In addition to the app (which is the sender), it is passed user, method, and token arguments.
New in version 3.3.0.
- us_security_token_sent¶
Sent when a unified sign in access code is sent. In addition to the app (which is the sender), it is passed user, method, token, phone_number, and send_magic_link arguments.
New in version 3.4.0.
- us_profile_changed¶
Sent when user completes changing their unified sign in profile. In addition to the app (which is the sender), it is passed user and method arguments.
New in version 3.4.0.