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

      * **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

      * **two_factor_verify_password_form** -- set form for the 2FA
        verify password view

      * **anonymous_user** -- class to use for anonymous user

      * **render_template** -- function to use to render templates.
        The default is Flask's render_template() function.

      * **send_mail** -- function to use to send email. Defaults to
        "send_mail()"

      * **json_encoder_cls** -- Class to use as
        blueprint.json_encoder. Defaults to "FsJsonEncoder"

   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.

   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 a "json_encoder" has been set on the blueprint
        corresponding to the current request. If not then it looks for
        a "json_encoder" registered on the app; and finally uses
        Flask's default JSONEncoder class. Flask-Security registers
        "FsJsonEncoder()" 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()" or
      "http_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()", or "permissions_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. For "login_required"
   (which is implemented in Flask-Login) use
   **flask_security.login_manager.unauthorized_handler**

   Deprecated 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

   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)

   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
      will be tried.

   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.

   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 of "token", "session", "basic" regardless of how they are
   specified in the "auth_methods" parameter.

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:

      1. *WTF_CSRF_ENABLED* is set to False

      2. the Flask-WTF CSRF module hasn't been initialized

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

   get_auth_token()

      Constructs the user's authentication token.

      This data MUST be securely signed using the
      "remember_token_serializer"

   get_redirect_qparams(existing=None)

      Return user info that will be added to redirect query params.

      New in version 3.2.0.

      Parameters:
         **existing** -- A dict that will be updated.

      Returns:
         A dict whose keys will be query params and values will be
         query values.

   get_security_payload()

      Serialize user object as response payload.

   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.

   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.

      New in version 3.2.0.

      Parameters:
         **password** -- A plaintext password to verify

   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.

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.

      Caller must commit to DB.

      New in version 3.3.0.

   get_permissions()

      Return set of permissions associated with role.

      New in version 3.3.0.

   remove_permissions(permissions)

      Remove one or more permissions from role.

      Parameters:
         **permissions** -- a set, list, or single string.

      Caller must commit to DB.

      New in version 3.3.0.

class flask_security.AnonymousUser

   AnonymousUser definition

   has_role(*args)

      Returns *False*


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

   Be aware that 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_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

   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

      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.

   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.

   get_user(id_or_email)

      Returns a user matching the specified ID or email address.

   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

   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 "fs_uniquifier"

      New in version 3.3.0.

   toggle_active(user)

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

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_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

   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

      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.

   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(**kwargs)

      Returns a user matching the provided parameters.

   get_user(identifier)

      Returns a user matching the specified ID or email address.

   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

   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 "fs_uniquifier"

      New in version 3.3.0.

   toggle_active(user)

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

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_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

   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

      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.

   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(**kwargs)

      Returns a user matching the provided parameters.

   get_user(identifier)

      Returns a user matching the specified ID or email address.

   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

   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 "fs_uniquifier"

      New in version 3.3.0.

   toggle_active(user)

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

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_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

   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

      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.

   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(**kwargs)

      Returns a user matching the provided parameters.

   get_user(identifier)

      Returns a user matching the specified ID or email address.

   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

   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 "fs_uniquifier"

      New in version 3.3.0.

   toggle_active(user)

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

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_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(**kwargs)

      Returns a user matching the provided parameters.

   get_user(identifier)

      Returns a user matching the specified ID or email address.

   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

   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 "fs_uniquifier"

      New in version 3.3.0.

   toggle_active(user)

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

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_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

   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

      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.

   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(**kwargs)

      Returns a user matching the provided parameters.

   get_user(identifier)

      Returns a user matching the specified ID or email address.

   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

   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 "fs_uniquifier"

      New in version 3.3.0.

   toggle_active(user)

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


Utils
=====

flask_security.login_user(user, remember=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"

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

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

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.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 via the Flask-Mail extension.

   Parameters:
      * **subject** -- Email subject

      * **recipient** -- Email recipient

      * **template** -- The name of the email template

      * **context** -- The context to render the template with

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

class flask_security.FsJsonEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

   Flask-Security JSON encoder. Extends Flask's JSONencoder to handle
   lazy-text.

   New in version 3.3.0.

class flask_security.SmsSenderBaseClass

   abstract send_sms(from_number, to_number, msg)

      Abstract method for sending sms messages

      New in version 3.2.0.

class flask_security.SmsSenderFactory

   classmethod createSender(name, *args, **kwargs)

      Initialize an SMS sender.

      Parameters:
         **name** -- Name as registered in SmsSenderFactory:senders
         (e.g. 'Twilio')

      New in version 3.2.0.


Signals
=======

See the Flask documentation on signals for information on how to use
these signals in your code.

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_registered

   Sent when a user registers on the site. In addition to the app
   (which is the sender), it is passed *user* and *confirm_token*
   arguments.

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.

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.

tf_disabled

   Sent when two-factor is disabled. In addition to the app (which is
   the sender), it is passed *user* argument.

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.
