API Docs

Extension

Invenio user management and authentication.

class invenio_accounts.ext.InvenioAccounts(app=None, sessionstore=None)[source]

Invenio-Accounts extension.

Extension initialization.

Parameters
  • app – The Flask application.

  • sessionstore – store for sessions. Passed to flask-kvsession. Defaults to redis.

check_configuration_consistency(app)[source]

Check if the config is consistent and issue a warning if not.

init_app(app, sessionstore=None, register_blueprint=True)[source]

Flask application initialization.

The following actions are executed:

  1. Initialize the configuration.

  2. Monkey-patch Flask-Security.

  3. Create the user datastore.

  4. Create the sessionstore.

  5. Initialize the extension, the forms to register users and confirms their emails, the CLI and, if ACCOUNTS_USE_CELERY is True, register a celery task to send emails.

  6. Override Flask-Security’s default login view function.

  7. Warn if inconsistent configuration is detected

Parameters
  • app – The Flask application.

  • sessionstore – store for sessions. Passed to flask-kvsession. If None then Redis is configured. (Default: None)

  • register_blueprint – If True, the application registers the blueprints. (Default: True)

init_config(app)[source]

Initialize configuration.

Parameters

app – The Flask application.

property jwt_creation_factory[source]

Load default JWT creation factory.

property jwt_decode_factory[source]

Load default JWT veryfication factory.

static monkey_patch_flask_security()[source]

Monkey-patch Flask-Security.

register_anonymous_identity_loader(state)[source]

Registers a loader for AnonymousIdentity.

Additional loader is necessary for applying a need ‘any-user’ to AnonymousUser in the invenio-access module

class invenio_accounts.ext.InvenioAccountsREST(app=None, sessionstore=None)[source]

Invenio-Accounts REST extension.

Extension initialization.

Parameters
  • app – The Flask application.

  • sessionstore – store for sessions. Passed to flask-kvsession. Defaults to redis.

init_app(app, sessionstore=None, register_blueprint=False)[source]

Flask application initialization.

Parameters
  • app – The Flask application.

  • sessionstore – store for sessions. Passed to flask-kvsession. If None then Redis is configured. (Default: None)

  • register_blueprint – If True, the application registers the blueprints. (Default: True)

class invenio_accounts.ext.InvenioAccountsUI(app=None, sessionstore=None)[source]

Invenio-Accounts UI extension.

Extension initialization.

Parameters
  • app – The Flask application.

  • sessionstore – store for sessions. Passed to flask-kvsession. Defaults to redis.

init_app(app, sessionstore=None, register_blueprint=True)[source]

Flask application initialization.

Parameters
  • app – The Flask application.

  • sessionstore – store for sessions. Passed to flask-kvsession. If None then Redis is configured. (Default: None)

  • register_blueprint – If True, the application registers the blueprints. (Default: True)

make_session_permanent(app)[source]

Make session permanent by default.

Set PERMANENT_SESSION_LIFETIME to specify time-to-live

Administration

Datastore

Session-aware datastore.

class invenio_accounts.datastore.SessionAwareSQLAlchemyUserDatastore(db, user_model, role_model)[source]

Datastore which deletes active session when a user is deactivated.

commit()[source]

Commit a user to its session.

create_role(**kwargs)[source]

Creates and returns a new role from the given parameters.

deactivate_user(user)[source]

Deactivate a user.

Parameters

user – A invenio_accounts.models.User instance.

Returns

The datastore instance.

find_role_by_id(role_id)[source]

Fetches roles searching by id.

mark_changed(sid, uid=None, rid=None)[source]

Save a user to the changed history.

update_role(role)[source]

Updates roles.

Errors

Exception classes.

exception invenio_accounts.errors.AlreadyLinkedError(user, external_id)[source]

Signifies that an account was already linked to another account.

Initialize exception.

exception invenio_accounts.errors.JWTDecodeError[source]

Exception raised when decoding is failed.

exception invenio_accounts.errors.JWTExpiredToken[source]

Exception raised when JWT is expired.

exception invenio_accounts.errors.JWTExtendedException[source]

Base exception for all JWT errors.

Forms

Additional non-userprofile fields used during registration.

Currently supported: recaptcha

class invenio_accounts.forms.RegistrationFormRecaptcha(*args, **kwargs)[source]

Form for editing user profile.

Parameters
  • formdata – Input data coming from the client, usually request.form or equivalent. Should provide a “multi dict” interface to get a list of values for a given key, such as what Werkzeug, Django, and WebOb provide.

  • obj – Take existing data from attributes on this object matching form field attributes. Only used if formdata is not passed.

  • prefix – If provided, all fields will have their name prefixed with the value. This is for distinguishing multiple forms on a single page. This only affects the HTML name for matching input data, not the Python name for matching existing data.

  • data – Take existing data from keys in this dict matching form field attributes. obj takes precedence if it also has a matching attribute. Only used if formdata is not passed.

  • meta – A dict of attributes to override on this form’s meta instance.

  • extra_filters – A dict mapping field attribute names to lists of extra filter functions to run. Extra filters run after filters passed when creating the field. If the form has filter_<fieldname>, it is the last extra filter.

  • kwargs – Merged with data to allow passing existing data as parameters. Overwrites any duplicate keys in data. Only used if formdata is not passed.

class invenio_accounts.forms.RevokeForm(*args, **kwargs)[source]

Form for revoking a session.

Parameters
  • formdata – Input data coming from the client, usually request.form or equivalent. Should provide a “multi dict” interface to get a list of values for a given key, such as what Werkzeug, Django, and WebOb provide.

  • obj – Take existing data from attributes on this object matching form field attributes. Only used if formdata is not passed.

  • prefix – If provided, all fields will have their name prefixed with the value. This is for distinguishing multiple forms on a single page. This only affects the HTML name for matching input data, not the Python name for matching existing data.

  • data – Take existing data from keys in this dict matching form field attributes. obj takes precedence if it also has a matching attribute. Only used if formdata is not passed.

  • meta – A dict of attributes to override on this form’s meta instance.

  • extra_filters – A dict mapping field attribute names to lists of extra filter functions to run. Extra filters run after filters passed when creating the field. If the form has filter_<fieldname>, it is the last extra filter.

  • kwargs – Merged with data to allow passing existing data as parameters. Overwrites any duplicate keys in data. Only used if formdata is not passed.

invenio_accounts.forms.confirm_register_form_factory(Form, app)[source]

Return confirmation for extended registration form.

invenio_accounts.forms.login_form_factory(Form, app)[source]

Return extended login form.

invenio_accounts.forms.register_form_factory(Form, app)[source]

Return extended registration form.

invenio_accounts.forms.send_confirmation_form_factory(Form, app)[source]

Return extended login form.

Hash

Legacy Invenio hash support.

class invenio_accounts.hash.InvenioAesEncryptedEmail(salt=None, **kwds)[source]

Invenio AES encryption of user email using password as secret key.

Invenio 1.x was AES encrypting the users email address with the password as the secret key and storing it in a blob column. This e.g. caused problems when a user wanted to change email address. This hashing engine, differs from Invenio 1.x in that it sha256 hashes the encrypted value as well to produce a string in the same length instead of a binary blob. It is not done for extra security, just for convenience of migration to using passlib’s sha512. An upgrade recipe is provided to migrated existing binary password hashes to hashes of this engine.

classmethod from_string(hash, **context)[source]

Parse instance from configuration string in Modular Crypt Format.

to_string()[source]

Render instance to configuration string in Modular Crypt Format.

Models

Database models for accounts.

class invenio_accounts.models.LoginInformation(**kwargs)[source]

Login information for a user.

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

current_login_at

When user logged into the current session.

current_login_ip

Current user IP address.

last_login_at

When the user logged-in for the last time.

last_login_ip

Last user IP address.

login_count

Count how many times the user logged in.

user

User to whom this information belongs.

user_id

ID of user to whom this information belongs.

validate_ip(key, value)[source]

Hack untrackable IP addresses.

class invenio_accounts.models.Role(**kwargs)[source]

Role data model.

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

created
description

Role description.

is_managed

True when the role is managed by Invenio, and not externally provided.

name

Role name.

updated
version_id

Used by SQLAlchemy for optimistic concurrency control.

class invenio_accounts.models.SessionActivity(**kwargs)[source]

User Session Activity model.

Instances of this model correspond to a session belonging to a user.

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

browser

User browser.

browser_version

Browser version.

country

Country name.

created
device

User device.

ip

IP address.

classmethod is_current(sid_s)[source]

Check if the session is the current one.

os

User operative system name.

classmethod query_by_expired()[source]

Query to select all expired sessions.

classmethod query_by_user(user_id)[source]

Query to select user sessions.

sid_s

Serialized Session ID. Used as the session’s key in the kv-session store employed by flask-kvsession. Named here as it is in flask-kvsession to avoid confusion.

updated
user_id

ID of user to whom this session belongs.

class invenio_accounts.models.User(*args, **kwargs)[source]

User data model.

Constructor.

active

Flag to say if the user is active or not .

confirmed_at

When the user confirmed the email address.

created
property current_login_at

When user logged into the current session.

property current_login_ip

Current user IP address.

email

User email.

property last_login_at

When the user logged-in for the last time.

property last_login_ip

Last user IP address.

property login_count

Count how many times the user logged in.

password

User password.

preferences

Get the user preferences.

roles

List of the user’s roles.

updated
user_profile

Get the user profile.

username

Get username.

version_id

Used by SQLAlchemy for optimistic concurrency control.

class invenio_accounts.models.UserIdentity(**kwargs)[source]

Represent a UserIdentity record.

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

classmethod create(user, method, external_id)[source]

Link a user to an external id.

Parameters
Raises

AlreadyLinkedError – Raised if already exists a link.

created
classmethod delete_by_external_id(method, external_id)[source]

Unlink a user from an external id.

classmethod delete_by_user(method, user)[source]

Unlink a user from an external id.

classmethod get_user(method, external_id)[source]

Get the user for a given identity.

updated
invenio_accounts.models.userrole = Table('accounts_userrole', MetaData(), Column('user_id', Integer(), ForeignKey('accounts_user.id'), table=<accounts_userrole>), Column('role_id', String(length=80), ForeignKey('accounts_role.id'), table=<accounts_userrole>), schema=None)

Relationship between users and roles.

Utils

Utility function for ACCOUNTS.

invenio_accounts.utils.change_user_password(_reset_password_link_func=None, **user_data)[source]

Change user password.

Return the confirmation link that will be sent to a user via email.

Return the reset password link that will be sent to a user via email.

invenio_accounts.utils.jwt_create_token(user_id=None, additional_data=None)[source]

Encode the JWT token.

Parameters
  • user_id (int) – Addition of user_id.

  • additional_data (dict) – Additional information for the token.

Returns

The encoded token.

Return type

str

Note

Definition of the JWT claims:

  • exp: ((Expiration Time) expiration time of the JWT.

  • sub: (subject) the principal that is the subject of the JWT.

  • jti: (JWT ID) UID for the JWT.

invenio_accounts.utils.jwt_decode_token(token)[source]

Decode the JWT token.

Parameters

token (str) – Additional information for the token.

Returns

The token data.

Return type

dict

invenio_accounts.utils.obj_or_import_string(value, default=None)[source]

Import string or return object.

Params value

Import path or class object to instantiate.

Params default

Default object to return if the import fails.

Returns

The imported object.

invenio_accounts.utils.register_user(_confirmation_link_func=None, send_register_msg=True, **user_data)[source]

Register a user.

invenio_accounts.utils.set_session_info(app, response, **extra)[source]

Add X-Session-ID and X-User-ID to http response.

invenio_accounts.utils.validate_username(username)[source]

Validate the username.

Parameters

username – The username to validate.

Raises

ValueError – If validation fails.

Testing utils

Invenio-Accounts utility functions for tests and testing purposes.

Warning

DO NOT USE IN A PRODUCTION ENVIRONMENT.

Functions within accessing the datastore will throw an error if called outside of an application context. If pytest-flask is installed you don’t have to worry about this.

invenio_accounts.testutils.client_authenticated(client, test_url=None)[source]

Attempt to access the change password page with the given client.

Parameters

test_url – URL to attempt to get. Defaults to the current application’s “change password” page.

Returns

True if the client can get the test_url without getting redirected and flask_login.current_user is not anonymous after requesting the page.

invenio_accounts.testutils.create_test_user(email, password='123456', **kwargs)[source]

Create a user in the datastore, bypassing the registration process.

Accesses the application’s datastore. An error is thrown if called from outside of an application context.

Returns the created user model object instance, with the plaintext password as user.password_plaintext.

Parameters
  • email – The user email.

  • password – The user password. (Default: 123456)

Returns

A invenio_accounts.models.User instance.

invenio_accounts.testutils.login_user_via_session(client, user=None, email=None)[source]

Login a user via the session.

Parameters
  • client – The CLI test client.

  • user – The invenio_accounts.models.User instance. Optional. (Default: None)

  • email – Load the user by the email. Optional. (Default: None)

invenio_accounts.testutils.login_user_via_view(client, email=None, password=None, user=None, login_url=None)[source]

Attempt to log the given user in via the ‘login’ view on the client.

Parameters
  • client – client to send the request from.

  • email – email of user account to log in with.

  • password – password of user account to log in with.

  • user (invenio_accounts.models.User (with the addition of a password_plaintext field)) – If present, user.email and user.password_plaintext take precedence over the email and password parameters.

  • login_url – URL to post login details to. Defaults to the current application’s login URL.

Returns

The response object from the POST to the login form.

invenio_accounts.testutils.unserialize_session(sid_s)[source]

Return the unserialized session.

Parameters

sid_s – The session ID.

Returns

The unserialized version.

invenio_accounts.testutils.webdriver_authenticated(webdriver, test_url=None)[source]

Attempt to get the change password page through the given webdriver.

Similar to client_authenticated, but for selenium webdriver objects.

Tasks

()invenio_accounts.tasks.send_security_email(data)[source]

Celery task to send security email.

Parameters

data – Contains the email data.

()invenio_accounts.tasks.clean_session_table()[source]

Automatically clean session table.

To enable a periodically clean of the session table, you should configure the task as a celery periodic task.

from datetime import timedelta
CELERYBEAT_SCHEDULE = {
    'session_cleaner': {
        'task': 'invenio_accounts.tasks.clean_session_table',
        'schedule': timedelta(days=1),
    },
}

See Invenio-Celery documentation for further details.

Views

Invenio user management and authentication.

invenio_accounts.views.security.revoke_session()[source]

Revoke a session.

invenio_accounts.views.security.security()[source]

View for security page.

Invenio user management and authentication.

invenio_accounts.views.settings.check_security_settings()[source]

Warn if session cookie is not secure in production.

invenio_accounts.views.settings.init_menu()[source]

Initialize menu before first request.