API

Core

class IdentityManager(app=None, db=None, user_model=None, role_model=None, register_blueprint=None, **kwargs)

Simple & Customizable User Authentication and Management.

Init IdentityManager with Flask(app), db, user_model and role_model

Parameters
  • appFlask(app) instance

  • db – An orm database instance.

  • user_model – The model class of user

  • role_model – The model class of role

  • register_blueprint – Register default blueprint

  • anonymous_user – The class of AnonymousUser based on AnonymousUserMixin

init_app(app, db=None, user_model=None, role_model=None, register_blueprint=None, **kwargs)

Init IdentityManager with Flask(app), db, user_model and role_model

Parameters
  • appFlask(app) instance

  • db – A database instance

  • user_model – The model class of user

  • role_model – The model class of role

  • register_blueprint – Register default blueprint

  • anonymous_user – The class of AnonymousUser based on AnonymousUserMixin

unauthenticated_handler(fn)

Register a custom unauthenticated handler. :param fn: Custom unauthenticated function.

unauthorized_handler(fn)

Register a custom unauthorized handler. :param fn: Custom unauthorized function.

template_render(fn)

Register a custom template render function. :param fn: Custom template render function.

get_current_user()
Try load UserMixin based instance from session,
if failed then try load from cookie,
if failed then try load from request.
Failed return AnonymousUserMixin based instance.
Returns

UserMixin or AnonymousUserMixin based instance.

unauthenticated(header=None)
If caller wants JSON - return 403
Otherwise - assume caller is html and redirect to IDENTITY_UNAUTHENTICATED_VIEW or 403
unauthorized(header=None)
If caller wants JSON - return 401
Otherwise - assume caller is html and redirect to IDENTITY_UNAUTHORIZED_VIEW or 401
update_request_context_with_user(user=None)
Parameters

user – User object

Returns

Store the given user as ctx.user.

property datastore

The datastore of Identity Manager

Type

return

flask_identity.current_user

A proxy for the current user.

flask_identity.current_identity

A proxy for the current Flask_Identity instance.

DataStore

class IdentityStore(user_model, role_model)

Abstracted user identity store.

Parameters
  • user_model – A user model class definition

  • role_model – A role model class definition

Be aware that for mutating operations, the user/role will be added to the store (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().

find_user(*args, **kwargs)

Returns a user matching the provided parameters.

find_role(*args, **kwargs)

Returns a role matching the provided name.

add_role_to_user(user, role)

Adds a role to a user.

Parameters
  • user – The user to manipulate. Can be an User object or lookup key id with 'IDENTITY_IDENTITY_FIELD'

  • role – The role to add to the user. Can be a Role object or string role name

remove_role_from_user(user, role)

Removes a role from a user.

Parameters
  • user – The user to manipulate. Can be an User object or lookup key id with 'IDENTIT_IDENTITY_FIELD'

  • role – The role to remove from the user. Can be a Role object or string role name

toggle_active(user)

Toggles a user’s active status. Always returns True.

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

activate_user(user)

Activates a specified user. Returns True if a change was made.

Parameters

user – The user to activate

set_uniquifier(user, uniquifier=None)

Set user’s authentication token uniquifier. 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 uniquifier

create_role(**kwargs)

Creates and returns a new role from the given parameters. Supported params (depending on RoleModel):

Keyword Arguments

name – Role name

create_user(**kwargs)

Creates and returns a new user from the given parameters.

Keyword Arguments
  • name – required.

  • password – Hashed password.

  • roles – list of roles to be added to user. Can be Role objects or strings

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).

The new user’s active property will be set to true.

delete_user(user)

Deletes the specified user.

Parameters

user – The user to delete

class PonyIdentityStore(db, user_model, role_model)

A Pony ORM identity store implementation of IdentityStore for IdentityManager.

class SQLAlchemyIdentityStore(db, user_model, role_model)

A SQLAlchemy identity store implementation of IdentityStore for IdentityManager.

Protecting Views

auth_required(*auth_methods)

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, session). If not specified then all current available mechanisms will be tried.

Note that regardless of order specified - they will be tried in the following order: token, session.

The first mechanism that succeeds is used, following that, depending on configuration.

On authentication failure IdentityManager.unauthenticated() will be called.

login_required(view_function)

Ensure that the current user is logged in and authenticated before calling the actual view.

For example:

@app.route('/post')
@login_required
def post():
    pass

Note

Per W3 guidelines for CORS preflight requests, HTTP OPTIONS requests are exempt from login checks.

Parameters

view_function (function) – The view function to decorate.

roles_required(*role_names)

This decorator ensures that the current user is logged in, and has all of the specified roles (AND operation).

Example:

@route('/escape')
@roles_required('Special', 'Agent')
def escape_capture():  # User must be 'Special' AND 'Agent'
    ...

Calls unauthenticated_view() when the user is not logged in or when user is not actived.

Calls unauthorized_view() when the user does not have the required roles.

Calls the decorated view otherwise.

roles_accepted(*role_names)

This decorator ensures that the current user is logged in, and has at least one of the specified roles (OR operation).

Example:

@route('/edit_article')
@roles_accepted('Writer', 'Editor')
def edit_article():  # User must be 'Writer' OR 'Editor'
    ...

Calls unauthenticated_view() when the user is not logged in or when user is not actived.

Calls unauthorized_view() when the user does not have the required roles.

Calls the decorated view otherwise.

User Object Helpers

class UserMixin

This class adds required methods to the User data-model.

Example

class User(db.Model, UserMixin):

has_roles(*requirements)

Return True if the user has all of the specified roles. Return False otherwise.

has_roles() accepts a list of requirements:

has_roles(requirement1, requirement2, requirement3).

Each requirement is either a role_name, or a tuple_of_role_names.

role_name example: ‘manager’ tuple_of_role_names: (‘funny’, ‘witty’, ‘hilarious’)

A role_name-requirement is accepted when the user has this role. A tuple_of_role_names-requirement is accepted when the user has ONE of these roles.

has_roles() returns true if ALL of the requirements have been accepted.

For example:

has_roles(‘a’, (‘b’, ‘c’), d)

Translates to:

User has role ‘a’ AND (role ‘b’ OR role ‘c’) AND role ‘d’

get_auth_token()

Constructs the user’s authentication token.

This data MUST be securely signed using the identity token_context

get_security_payload()

Serialize user object as response payload.

verify_password(passwd)

Verify password

class RoleMixin

Mixin for Role model definitions

class AnonymousUserMixin

This is the default object for representing an anonymous user.

Utils

login_user(user: flask_identity.mixins.UserMixin, uniquifier=None, remember=None, duration=None, fresh=True)

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.

  • uniquifier (str) – The uniquifier for isolate login session. If None will use a uuid.hex() as default. Defatuls to None.

  • remember (bool) – Whether to remember the user after their session expires. Defaults to IDENTITY_REMEMBER_ME.

  • 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.

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

logout_user()

Logs a user out. (You do not need to pass the actual user.) This will also clean up the remember me cookie if it exists.

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)

hash_password(password)

Hash the specified plaintext password. :param password: The plaintext password to hash :return: The hashed password

url_for_identity(endpoint, **values)

Return a URL for the Flask-Identity blueprint.

This is method is a wrapper of :meth:Flask.url_for.

Parameters
  • endpoint – the endpoint of the URL (name of the function)

  • values – the variable arguments of the URL rule