From 09ef6197d2e40a5be397c271fc1abdb1c2ab6e3a Mon Sep 17 00:00:00 2001
From: sandeepsajan0 <sandeepsajan0@gmail.com>
Date: Wed, 13 Apr 2022 12:28:11 +0530
Subject: [PATCH] Add Docstring in middleware and update test class name

---
 hypha/apply/users/middleware.py            | 14 ++++++++++++--
 hypha/apply/users/tests/test_middleware.py |  2 +-
 2 files changed, 13 insertions(+), 3 deletions(-)

diff --git a/hypha/apply/users/middleware.py b/hypha/apply/users/middleware.py
index b52be3d48..b466c1d49 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 0378f5fb3..9f1263a50 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')
 
-- 
GitLab