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:
Initialize the configuration.
Monkey-patch Flask-Security.
Create the user datastore.
Create the sessionstore.
Initialize the extension, the forms to register users and confirms their emails, the CLI and, if
ACCOUNTS_USE_CELERY
isTrue
, register a celery task to send emails.Override Flask-Security’s default login view function.
Warn if inconsistent configuration is detected
- Parameters
app – The Flask application.
sessionstore – store for sessions. Passed to
flask-kvsession
. IfNone
then Redis is configured. (Default:None
)register_blueprint – If
True
, the application registers the blueprints. (Default:True
)
- 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
. IfNone
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
. IfNone
then Redis is configured. (Default:None
)register_blueprint – If
True
, the application registers the blueprints. (Default:True
)
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.
- deactivate_user(user)[source]¶
Deactivate a user.
- Parameters
user – A
invenio_accounts.models.User
instance.- Returns
The datastore instance.
Errors¶
Exception classes.
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 ifformdata
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 indata
. Only used ifformdata
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 ifformdata
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 indata
. Only used ifformdata
is not passed.
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.
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.
- 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.
- 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.
- os¶
User operative system name.
- 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
user – A
invenio_accounts.models.User
instance.method – The identity source (e.g. orcid, github)
method – The external identifier.
- Raises
AlreadyLinkedError – Raised if already exists a link.
- created¶
- updated¶
- invenio_accounts.models.userrole = Table('accounts_userrole', MetaData(), Column('user_id', Integer(), ForeignKey('accounts_user.id'), table=<accounts_userrole>), Column('role_id', Integer(), 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.
- invenio_accounts.utils.default_confirmation_link_func(user)[source]¶
Return the confirmation link that will be sent to a user via email.
- invenio_accounts.utils.default_reset_password_link_func(user)[source]¶
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
- Returns
The encoded token.
- Return type
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.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 apassword_plaintext
field)) – If present,user.email
anduser.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.
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 user management and authentication.
- invenio_accounts.views.settings.check_security_settings()[source]¶
Warn if session cookie is not secure in production.
Initialize menu before first request.