justinmayer / kagi

WebAuthn security keys and TOTP multi-factor authentication for Django
BSD 2-Clause "Simplified" License
91 stars 10 forks source link

Require MFA verification on a view #70

Open MarkusH opened 1 year ago

MarkusH commented 1 year ago

This is a feature request that stems from https://github.com/justinmayer/kagi/issues/60.

Feature request

As a developer, I'd like to ensure a specific view is only accessible when the user went through a successful multi-factor verification. Since I'm using function based views and class based views, I'd like to have a decorator and a mixin that I can use in accordance to similar features within Django (e.g. @login_required and LoginRequired).

This ticket likely requires #68 before it can be implemented.

Implementation idea

from functools import wraps

def mfa_required(view):
    @wraps(view)
    def inner(request, *args, **kwargs):
        if not request.session.get("kagi_verified", False):  # See #68
            return redirect("kagi:verify-second-factor")
        return view(request, *args, **kwargs)

    return inner
class MFARequiredMixin:
    def dispatch(self, request, *args, **kwargs):
        if not request.session.get("kagi_verified", False):  # See #68
            return redirect("kagi:verify-second-factor")
        return super().dispatch(request, *args, **kwargs)