Middleware

TwoFactorAuthPropsMiddleware

Provides the system’s two-factor authentication configuration information to the frontend, under the tfa. prop.

class TwoFactorAuthPropsMiddleware:
     def __init__(self, get_response):
         self.get_response = get_response
         # One-time configuration and initialization.

     def __call__(self, request):
         if request.user.is_authenticated:
             if app_settings.DEFAULT_2FA_METHOD == app_settings.TwoFactoAuthMethod.OTP:
                 try:
                     setup_2fa = models.Otp.objects.get(user=request.user)
                 except models.Otp.DoesNotExist:
                     setup_2fa = False

             tfa = {
                 "enable": app_settings.ENABLE_2FA,
                 "userSetup": True if setup_2fa else False,
                 "method": app_settings.DEFAULT_2FA_METHOD,
             }
         else:
             tfa = {"enable": "", "userSetup": "", "method": ""}

         share(request, "tfa", tfa)

         response = self.get_response(request)
         return response

TwoFactorAuthMiddleware

Checks if the user has performed two-factor authentication in the current session. If it has, it redirects it to the view for authentication.

class TwoFactorAuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.user.is_authenticated:
            if (
                app_settings.ENABLE_2FA
                and app_settings.DEFAULT_2FA_METHOD
                == app_settings.TwoFactoAuthMethod.OTP
            ):
                otp = models.Otp.objects.filter(user=request.user)
                if not otp:
                    return None

                url = request.path.split("/")
                if url[1] or "2fa" in url[1] or "ip" in url[1]:
                    return None

                if len(url) > 0 and "admin" in url[1]:
                    return None

                tfa_verified = request.session.get("tfa_user_verified", False)

                if tfa_verified:
                    return None
                else:
                    return redirect("2fa:auth_otp")

        return None