Flask-User API


DBManager class

This class manages database objects.

class DBManager(app, db, UserClass, UserEmailClass=None, UserInvitationClass=None, RoleClass=None)

Manage DB objects.

Initialize the appropriate DbAdapter, based on the db parameter type.

Parameters:
  • app (Flask) – The Flask application instance.
  • db – The Object-Database Mapper instance.
  • UserClass – The User class.
  • UserEmailClass – Optional UserEmail class for multiple-emails-per-user feature.
  • UserInvitationClass – Optional UserInvitation class for user-invitation feature.
  • RoleClass – For testing purposes only.
add_user_role(user, role_name)

Associate a role name with a user.

add_user(**kwargs)

Add a User object, with properties specified in **kwargs.

add_user_email(user, **kwargs)

Add a UserEmail object, with properties specified in **kwargs.

add_user_invitation(**kwargs)

Add a UserInvitation object, with properties specified in **kwargs.

commit()

Commit session-based objects to the database.

delete_object(object)

Delete and object.

find_user_by_username(username)

Find a User object by username.

find_user_emails(user)

Find all the UserEmail object belonging to a user.

get_primary_user_email_object(user)

Retrieve the email from User object or the primary UserEmail object (if multiple emails per user are enabled).

get_user_and_user_email_by_id(user_or_user_email_id)

Retrieve the User and UserEmail object by ID.

get_user_and_user_email_by_email(email)

Retrieve the User and UserEmail object by email address.

get_user_by_id(id)

Retrieve a User object by ID.

get_user_email_by_id(id)

Retrieve a UserEmail object by ID.

get_user_invitation_by_id(id)

Retrieve a UserInvitation object by ID.

get_user_roles(user)

Retrieve a list of user role names.

Note

Database management methods.

save_object(object)

Save an object to the database.

save_user_and_user_email(user, user_email)

Save the User and UserEmail object.

user_has_confirmed_email(user)
Return True if user has a confirmed email.
Return False otherwise.
username_is_available(new_username)

Check if new_username is still available.

Returns True if new_username does not exist or belongs to the current user.
Return False otherwise.
create_all_tables()

Create database tables for all known database data-models.

drop_all_tables()

Drop all tables.

Warning

ALL DATA WILL BE LOST. Use only for automated testing.


EmailManager class

This class manages the sending of Flask-User emails.

class EmailManager(app)

Send emails via the configured EmailAdapter user_manager.email_adapter.

Parameters:app (Flask) – The Flask application instance.
send_confirm_email_email(user, user_email)

Send the ‘email confirmation’ email.

send_password_changed_email(user)

Send the ‘password has changed’ notification email.

send_reset_password_email(user, user_email)

Send the ‘reset password’ email.

send_invite_user_email(user, user_invitation)

Send the ‘user invitation’ email.

send_registered_email(user, user_email, request_email_confirmation)

Send the ‘user has registered’ notification email.

send_username_changed_email(user)

Send the ‘username has changed’ notification email.


PasswordManager class

The PasswordManager generates and verifies hashed passwords.

class PasswordManager(app)

Hash and verify user passwords using passlib

Create a passlib CryptContext.

Parameters:password_hash (str) – The name of a valid passlib password hash. Examples: 'bcrypt', 'pbkdf2_sha512', 'sha512_crypt' or 'argon2'.

Example

password_manager = PasswordManager('bcrypt')

hash_password(password)

Hash plaintext password using the password_hash specified in the constructor.

Parameters:password (str) – Plaintext password that the user types in.
Returns:hashed password.

Example

user.password = hash_password('mypassword')

verify_password(password, password_hash)

Verify plaintext password against hashed password.

Parameters:
  • password (str) – Plaintext password that the user types in.
  • password_hash (str) – Password hash generated by a previous call to hash_password().
Returns:

True when password matches password_hash.
False otherwise.

Example

if verify_password('mypassword', user.password):
    login_user(user)

TokenManager class

The TokenManager generates and verifies timestamped, signed and encrypted tokens.

These tokens are used in the following places:

  • To securely store User IDs in the browser session cookie.
  • To provide secure tokens in email-confirmation emails.
  • To provide secure tokens in reset-password emails.
class TokenManager(app)

Generate and verify timestamped, signed and encrypted tokens.

Check config settings and initialize the Fernet encryption cypher.

Fernet is basically AES128 in CBC mode, with a timestamp and a signature.

Parameters:app (Flask) – The Flask application instance.
generate_token(*args)

Convert a list of integers or strings, specified by *args, into an encrypted, timestamped, and signed token.

Note: strings may not contain any '|' characters, nor start with a '~' character as these are used as separators and integer indicators for encoding.

Example:

# Combine User ID with last 8 bytes of their password
# to invalidate tokens when passwords change.
user_id = user.id
password_ends_with = user.password[-8:0]
token = token_manager.generate_token(user_id, password_ends_with)
verify_token(token, expiration_in_seconds=None)

Verify token signature, verify token expiration, and decrypt token.

Returns None if token is expired or invalid.
Returns a list of strings and integers on success.

Implemented as:

concatenated_str = self.decrypt_string(token, expiration_in_seconds)
data_items = self.decode_data_items(concatenated_str)
return data_items

Example:

# Verify that a User with ``user_id`` has a password that ends in ``password_ends_with``.
token_is_valid = False
data_items = token_manager.verify(token, expiration_in_seconds)
if data_items:
    user_id = data_items[0]
    password_ends_with = data_items[1]
    user = user_manager.db_manager.get_user_by_id(user_id)
    token_is_valid = user and user.password[-8:]==password_ends_with
encrypt_string(concatenated_str)

Timestamp, sign and encrypt a string into a token using cryptography.fernet.Fernet().

decrypt_string(token_str, expiration_in_seconds=None)

Verify signature, verify timestamp, and decrypt a token using cryptography.fernet.Fernet().

encode_data_items(*args)

Encodes a list of integers and strings into a concatenated string.

  • encode string items as-is.
  • encode integer items as base-64 with a '~' prefix.
  • concatenate encoded items with a '|' separator.

Example

encode_data_items('abc', 123, 'xyz') returns 'abc|~B7|xyz'

decode_data_items(concatenated_str)

Decodes a concatenated string into a list of integers and strings.

Example

decode_data_items('abc|~B7|xyz') returns ['abc', 123, 'xyz']

encode_int(n)

Encodes an integer into a short Base64 string.

Example

encode_int(123) returns 'B7'.

decode_int(str)

Decodes a short Base64 string into an integer.

Example

decode_int('B7') returns 123.