diff --git a/hypha/apply/users/middleware.py b/hypha/apply/users/middleware.py index b52be3d4827cfa638eca32100549cc4e4937d70e..b466c1d49bd6d96ec3064568aa358cd9cf29030b 100644 --- a/hypha/apply/users/middleware.py +++ b/hypha/apply/users/middleware.py @@ -24,6 +24,14 @@ class SocialAuthExceptionMiddleware(_SocialAuthExceptionMiddleware): class TwoFactorAuthenticationMiddleware: + """ + Middleware to enforce 2FA activation for unverified users + + To activate this middleware set env variable ENFORCE_TWO_FACTOR as True. + + This will redirect all request from unverified users to enable 2FA first. + Except the request made on the url paths listed in ALLOWED_SUBPATH_FOR_UNVERIFIED_USERS. + """ def __init__(self, get_response): self.get_response = get_response @@ -37,8 +45,10 @@ class TwoFactorAuthenticationMiddleware: def __call__(self, request): # code to execute before the view user = request.user - if settings.ENFORCE_TWO_FACTOR and user.is_authenticated and not user.is_verified() and not self.is_path_allowed(request.path): - return redirect('/account/two_factor/required/') + if settings.ENFORCE_TWO_FACTOR: + if user.is_authenticated and not user.is_verified(): + if not self.is_path_allowed(request.path): + return redirect('/account/two_factor/required/') response = self.get_response(request) diff --git a/hypha/apply/users/tests/test_middleware.py b/hypha/apply/users/tests/test_middleware.py index 0378f5fb3c1a95c8867d688bee5bd9574c2701d7..9f1263a50e4c9b29745142933d3e45fd7dd4e00a 100644 --- a/hypha/apply/users/tests/test_middleware.py +++ b/hypha/apply/users/tests/test_middleware.py @@ -8,7 +8,7 @@ from ..middleware import ALLOWED_SUBPATH_FOR_UNVERIFIED_USERS @override_settings(ROOT_URLCONF='hypha.apply.urls') -class TestTwoFAMiddleware(TestCase): +class TestTwoFactorAuthenticationMiddleware(TestCase): def enable_otp(self, user): return user.totpdevice_set.create(name='default')