View decorators

Flask-User view decorators serve as the gatekeepers to prevent unauthenticated or unauthorized users from accessing certain views.

Important

The @route decorator must always be the first view decorator in a list of view decorators (because it’s used to map the function below itself to a URL).

login_required(view_function)

This decorator ensures that the current user is logged in.

Example:

@route('/member_page')
@login_required
def member_page():  # User must be logged in
    ...

If USER_ENABLE_EMAIL is True and USER_ENABLE_CONFIRM_EMAIL is True, this view decorator also ensures that the user has a confirmed email address.

Calls unauthorized_view() when the user is not logged in or when the user has not confirmed their email address.
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 has not confirmed their email address.
Calls unauthorized_view() when the user does not have the required roles.
Calls the decorated view otherwise.
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 has not confirmed their email address.
Calls unauthorized_view() when the user does not have the required roles.
Calls the decorated view otherwise.
allow_unconfirmed_email(view_function)

This decorator ensures that the user is logged in, but allows users with or without a confirmed email addresses to access this particular view.

It works in tandem with the USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL=True setting.

Caution

Use USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL=True and @allow_unconfirmed_email with caution, as they relax security requirements.
Make sure that decorated views never call other views directly. Allways use redirect() to ensure proper view protection.

Example:

@route('/show_promotion')
@allow_unconfirmed_emails
def show_promotion():   # Logged in, with or without
    ...                 # confirmed email address

It can also precede the @roles_required and @roles_accepted view decorators:

@route('/show_promotion')
@allow_unconfirmed_emails
@roles_required('Visitor')
def show_promotion():   # Logged in, with or without
    ...                 # confirmed email address
Calls unauthorized_view() when the user is not logged in.
Calls the decorated view otherwise.