Skip to content

2.4.0

Compare
Choose a tag to compare
@CheeseCake87 CheeseCake87 released this 22 Sep 14:50
  1. Doc strings overhauled, example uses can now be seen in the doc strings.
  2. Addition of a new method in the security package.

include_crsf()

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 abort(abort_code), default 401.

@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"))
def include_csrf(session_key: str = "csrf", form_key: str = "csrf", abort_code: int = 401):
    def include_csrf_wrapper(func):
        @wraps(func)
        def inner(*args, **kwargs):
            if request.method == "GET":
                session[session_key] = Auth.generate_form_token()

                return func(*args, **kwargs)

            if request.method == "POST":
                _session_key = session.get(session_key)
                _form_key = request.form.get(form_key)

                if _form_key is None:
                    return abort(abort_code)

                if _session_key is None:
                    return abort(abort_code)

                if _session_key != _form_key:
                    return abort(abort_code)

            return func(*args, **kwargs)

        return inner

    return include_csrf_wrapper