flask_imp.security

This module contains the security utilities for a Flask application.

Functions:

  • api_login_check: Checks if the user is logged in for an API request using sessions.

  • include_csrf: Includes a CSRF token in a GET response, and checks it during a POST request.

  • login_check: Checks if the user is logged in using sessions.

  • permission_check: Checks if the user has the required permissions using sessions.

  • pass_function_check: Checks is a function you give passes before hitting a route.

flask_imp.security.api_login_check(session_key, values_allowed, fail_json=None, fail_status=401)

A decorator that is used to secure API routes using the session.

Example of a route that requires a user to be logged in:

@bp.route("/api/resource", methods=["GET"])
@api_login_check('logged_in', True)
def api_page():
    ...

You can also supply your own failed return JSON:

@bp.route("/api/resource", methods=["GET"])
@api_login_check('logged_in', True, fail_json={"error": "You are not logged in."})
def api_page():
    ...

Note: Using this on a route will require you to include credentials on the request.

Here’s an example using JavaScript fetch():

fetch("/api/resource", {
    method: "GET",
    credentials: "include"
})
Parameters:
  • session_key (str) – the session key to check for

  • values_allowed (List[str | int | bool] | str | int | bool) – a list of or singular value(s) that the session key must contain

  • fail_json (Dict[str, Any] | None) – JSON that is returned on failure - defaults to {“error”: “You are not logged in.”}

  • fail_status (int) – the status code to return on failure - defaults to 401

Returns:

the decorated function, or a JSON fail response

Return type:

Callable[[…], Any]

flask_imp.security.include_csrf(session_key='csrf', form_key='csrf', abort_status=401)

A decorator that handles CSRF protection.

On a GET request, a CSRF token is generated and stored in the session key specified by the session_key parameter.

On a POST request, the form_key specified is checked against the session_key specified.

If they match, the request is allowed to continue.

If no match, the response will be aborted, flask.abort(abort_code), default 401.

Example of a route that requires CSRF protection:

@bp.route("/admin", methods=["GET", "POST"])
@include_csrf(session_key="csrf", form_key="csrf")
def admin_page():
    ...
    # You must pass in the CSRF token from the session into the template.
    # Then add <input type="hidden" name="csrf" value="{{ csrf }}"> to the form.
    return render_template("admin.html", csrf=session.get("csrf"))
Parameters:
  • session_key (str) – session key to store the CSRF token in.

  • form_key (str) – form key to check against the session key.

  • abort_status (int) – abort status code to use if the CSRF check fails.

Returns:

decorated function, or abort(abort_code) response.

Return type:

Callable[[…], Any]

flask_imp.security.login_check(session_key, values_allowed, fail_endpoint=None, pass_endpoint=None, endpoint_kwargs=None, message=None, message_category='message', abort_status=403)

A decorator that checks if the specified session key exists and contains the specified value.

Example of a route that requires a user to be logged in:

@bp.route("/admin", methods=["GET"])
@login_check(
    'logged_in',
    True,
    fail_endpoint='blueprint.login_page',
    message="Login needed"
)
def admin_page():
    ...

Example of a route that if the user is already logged in, redirects to the specified endpoint:

@bp.route("/login-page", methods=["GET"])
@login_check(
    'logged_in',
    True,
    pass_endpoint='blueprint.admin_page',
    message="Already logged in"
)
def login_page():
    ...
Parameters:
  • session_key (str) – the session key to check for

  • values_allowed (List[str | int | bool] | str | int | bool) – a list of or singular value(s) that the session key must contain

  • fail_endpoint (str | None) – the endpoint to redirect to if the session key does not exist or match the pass_value

  • pass_endpoint (str | None) – the endpoint to redirect to if the session key passes Used to redirect away from login pages, if already logged in

  • endpoint_kwargs (Dict[str, str | int] | None) – a dictionary of keyword arguments to pass to the redirect endpoint

  • message (str | None) – a message to add to flask.flash()

  • message_category (str) – the category of the flash message

  • abort_status (int) – the status code to abort with if the session key does not exist or match the pass_value

Returns:

the decorated function, or abort(abort_code) response

Return type:

Callable[[…], Any]

flask_imp.security.pass_function_check(function, predefined_args=None, fail_endpoint=None, pass_endpoint=None, endpoint_kwargs=None, message=None, message_category='message', fail_on_missing_kwargs=False, abort_status=403)

A decorator that takes the result of a function and checks if it is True or False.

Useful for feature flags or other checks that need to be done before a route is accessed.

URL variables from @route will be read by this decorator. To use URL variables in your passed in function, make sure your functions argument(s) name(s) match the name(s) of the URL variable(s).

Example function:

def check_if_number(value):
    if isinstance(value, int):
        if value > 10:
            return True
    return False

Example of checking route variable:

@bp.route("/number/<int:value>", methods=["GET"])
@pass_function_check(
    check_if_number,
    fail_endpoint="wrong_number",
    message="Failed message"
)
def number():
    ...

Example of using predefined_args:

@bp.route("/number", methods=["GET"])
@pass_function_check(
    check_if_number,
    predefined_args={"value": os.getenv("NUMBER")},
    fail_endpoint="www.index",
    message="Failed message"
)
def number():
    ...
Parameters:
  • function (Callable[[...], Any]) – the function to call this will be passed the url variables of the route

  • predefined_args (Dict[str, Any] | None) – a dictionary of predefined arguments to pass to the function. Any keys that match any URL variables will overwrite the URL variable specified in @route

  • fail_endpoint (str | None) – the endpoint to redirect to if the session key does not exist or does not contain the specified values

  • pass_endpoint (str | None) – the endpoint to redirect to if the function check passes

  • endpoint_kwargs (Dict[str, str | int] | None) – a dictionary of keyword arguments to pass to the redirect endpoint

  • message (str | None) – if a message is specified, a flash message is shown

  • message_category (str) – the category of the flash message

  • fail_on_missing_kwargs (bool) – if any of the required arguments for the passed in function are missing from the url variables, force function result to False

  • abort_status (int) – the status code to abort with if the function check fails

Returns:

the decorated function, or abort(abort_status) response

Return type:

Callable[[…], Any]

flask_imp.security.permission_check(session_key, values_allowed, fail_endpoint=None, endpoint_kwargs=None, message=None, message_category='message', abort_status=403)

A decorator that checks if the specified session key exists and its value(s) match the specified value(s).

Example:

@bp.route("/admin-page", methods=["GET"])
@login_check('logged_in', True, 'blueprint.login_page')
@permission_check('permissions', ['admin'], fail_endpoint='www.index', message="Failed message")
def admin_page():
    ...
Parameters:
  • session_key (str) – the session key to check for

  • values_allowed (List[str | int | bool] | str | int | bool) – a list of or singular value(s) that the session key must contain

  • fail_endpoint (str | None) – the endpoint to redirect to if the session key does not exist or does not contain the specified values

  • endpoint_kwargs (Dict[str, str | int] | None) – a dictionary of keyword arguments to pass to the redirect endpoint

  • message (str | None) – if a message is specified, a flash message is shown

  • message_category (str) – the category of the flash message

  • abort_status (int) – the status code to abort with if the session key does not exist or match the pass_value

Returns:

The decorated function, or abort(abort_status) response

Return type:

Callable[[…], Any]

flask_imp.security.api_checkpoint(session_key, values_allowed, fail_json=None, fail_status=401)

A decorator that is used to secure API routes using the session.

Example of a route that requires a user to be logged in:

@bp.route("/api/resource", methods=["GET"])
@api_checkpoint('logged_in', True)
def api_page():
    ...

You can also supply your own failed return JSON:

@bp.route("/api/resource", methods=["GET"])
@api_checkpoint('logged_in', True, fail_json={"error": "You are not logged in."})
def api_page():
    ...

Example of a route that requires a user to be logged in and to be an admin:

@bp.route("/api/resource", methods=["GET"])
@api_checkpoint('logged_in', True)
@api_checkpoint('user_type', 'admin', fail_json={"error": "You are not an admin."})
def api_page():
    ...

Note: Using this on a route will require you to include credentials on the request.

Here’s an example using JavaScript fetch():

fetch("/api/resource", {
    method: "GET",
    credentials: "include"
})
Parameters:
  • session_key (str) – the session key to check for

  • values_allowed (List[str | int | bool] | str | int | bool) – a list of or singular value(s) that the session key must contain

  • fail_json (Dict[str, Any] | None) – JSON that is returned on failure - defaults to {“error”: “You are not logged in.”}

  • fail_status (int) – the status code to return on failure - defaults to 401

Returns:

the decorated function, or a JSON fail response

Return type:

Callable[[…], Any]

flask_imp.security.checkpoint(session_key, values_allowed, fail_endpoint=None, pass_endpoint=None, endpoint_kwargs=None, message=None, message_category='message', abort_status=403)

A decorator that checks if the specified session key exists and contains the specified value.

Example of a route that requires a user to be logged in:

@bp.route("/admin", methods=["GET"])
@checkpoint(
    'logged_in',
    True,
    fail_endpoint='blueprint.login_page',
    message="Login needed"
)
def admin_page():
    ...

Example of a route that if the user is already logged in, redirects to the specified endpoint:

@bp.route("/login-page", methods=["GET"])
@checkpoint(
    'logged_in',
    True,
    pass_endpoint='blueprint.admin_page',
    message="Already logged in"
)
def login_page():
    ...

Example of a route that requires a user to be logged in and to be an admin:

@bp.route("/admin", methods=["GET"])
@checkpoint(
    'logged_in',
    True,
    fail_endpoint='blueprint.login_page',
    message="Login needed"
)
@checkpoint(
    'user_type',
    'admin',
    fail_endpoint='blueprint.index',
    message="You need to be an admin to access this page"
)
def admin_page():
    ...
Parameters:
  • session_key (str) – the session key to check for

  • values_allowed (List[str | int | bool] | str | int | bool) – a list of or singular value(s) that the session key must contain

  • fail_endpoint (str | None) – the endpoint to redirect to if the session key does not exist or match the pass_value

  • pass_endpoint (str | None) – the endpoint to redirect to if the session key passes Used to redirect away from login pages, if already logged in

  • endpoint_kwargs (Dict[str, str | int] | None) – a dictionary of keyword arguments to pass to the redirect endpoint

  • message (str | None) – a message to add to flask.flash()

  • message_category (str) – the category of the flash message

  • abort_status (int) – the status code to abort with if the session key does not exist or match the pass_value

Returns:

the decorated function, or abort(abort_code) response

Return type:

Callable[[…], Any]