Skip to content

Commit a57ab63

Browse files
committed
fix: lint and format
1 parent 4b524de commit a57ab63

File tree

7 files changed

+47
-50
lines changed

7 files changed

+47
-50
lines changed

todo/middlewares/jwt_auth.py

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,7 @@ def __call__(self, request):
4747
],
4848
)
4949
return JsonResponse(
50-
data=error_response.model_dump(mode="json", exclude_none=True),
51-
status=status.HTTP_401_UNAUTHORIZED
50+
data=error_response.model_dump(mode="json", exclude_none=True), status=status.HTTP_401_UNAUTHORIZED
5251
)
5352

5453
except (TokenMissingError, TokenExpiredError, TokenInvalidError) as e:
@@ -67,8 +66,7 @@ def __call__(self, request):
6766
],
6867
)
6968
return JsonResponse(
70-
data=error_response.model_dump(mode="json", exclude_none=True),
71-
status=status.HTTP_401_UNAUTHORIZED
69+
data=error_response.model_dump(mode="json", exclude_none=True), status=status.HTTP_401_UNAUTHORIZED
7270
)
7371

7472
def _try_authentication(self, request) -> bool:
@@ -103,28 +101,28 @@ def _try_google_refresh(self, request) -> bool:
103101
"""Try to refresh Google access token"""
104102
try:
105103
refresh_token = request.COOKIES.get("ext-refresh")
106-
104+
107105
if not refresh_token:
108106
return False
109-
107+
110108
payload = validate_google_refresh_token(refresh_token)
111-
109+
112110
user_data = {
113111
"user_id": payload["user_id"],
114112
"google_id": payload["google_id"],
115113
"email": payload["email"],
116114
"name": payload.get("name", ""),
117115
}
118-
116+
119117
new_access_token = generate_google_access_token(user_data)
120-
118+
121119
self._set_google_user_data(request, payload)
122120

123121
request._new_access_token = new_access_token
124122
request._access_token_expires = settings.GOOGLE_JWT["ACCESS_TOKEN_LIFETIME"]
125-
123+
126124
return True
127-
125+
128126
except (GoogleRefreshTokenExpiredError, GoogleTokenInvalidError):
129127
return False
130128
except Exception:
@@ -161,13 +159,10 @@ def _try_rds_auth(self, request) -> bool:
161159

162160
def _process_response(self, request, response):
163161
"""Process response and set new cookies if Google token was refreshed"""
164-
if hasattr(request, '_new_access_token'):
162+
if hasattr(request, "_new_access_token"):
165163
config = self._get_cookie_config()
166164
response.set_cookie(
167-
"ext-access",
168-
request._new_access_token,
169-
max_age=request._access_token_expires,
170-
**config
165+
"ext-access", request._new_access_token, max_age=request._access_token_expires, **config
171166
)
172167
return response
173168

@@ -191,8 +186,7 @@ def _handle_rds_auth_error(self, exception):
191186
errors=[ApiErrorDetail(title=ApiErrors.AUTHENTICATION_FAILED, detail=str(exception))],
192187
)
193188
return JsonResponse(
194-
data=error_response.model_dump(mode="json", exclude_none=True),
195-
status=status.HTTP_401_UNAUTHORIZED
189+
data=error_response.model_dump(mode="json", exclude_none=True), status=status.HTTP_401_UNAUTHORIZED
196190
)
197191

198192
def _handle_google_auth_error(self, exception):
@@ -202,8 +196,7 @@ def _handle_google_auth_error(self, exception):
202196
errors=[ApiErrorDetail(title=ApiErrors.AUTHENTICATION_FAILED, detail=str(exception))],
203197
)
204198
return JsonResponse(
205-
data=error_response.model_dump(mode="json", exclude_none=True),
206-
status=status.HTTP_401_UNAUTHORIZED
199+
data=error_response.model_dump(mode="json", exclude_none=True), status=status.HTTP_401_UNAUTHORIZED
207200
)
208201

209202

@@ -240,4 +233,4 @@ def get_current_user_info(request) -> dict:
240233
}
241234
)
242235

243-
return user_info
236+
return user_info

todo/tests/integration/base_mongo_test.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@ def setUpClass(cls):
2020
cls.db = cls.mongo_client.get_database("testdb")
2121

2222
cls.override = override_settings(
23-
MONGODB_URI=cls.mongo_url,
24-
DB_NAME="testdb",
25-
FRONTEND_URL="http://localhost:4000"
23+
MONGODB_URI=cls.mongo_url, DB_NAME="testdb", FRONTEND_URL="http://localhost:4000"
2624
)
2725
cls.override.enable()
2826
DatabaseManager.reset()
@@ -77,4 +75,4 @@ def get_user_model(self) -> UserModel:
7775
name=self.user_data["name"],
7876
createdAt=datetime.now(timezone.utc),
7977
updatedAt=datetime.now(timezone.utc),
80-
)
78+
)

todo/tests/unit/middlewares/test_jwt_auth.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from unittest import TestCase
22
from unittest.mock import Mock, patch
33
from django.http import HttpRequest, JsonResponse
4-
from django.conf import settings
54
from rest_framework import status
65
import json
76

todo/tests/unit/views/test_auth.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def setUp(self):
108108
self.url = reverse("google_callback")
109109
self.factory = APIRequestFactory()
110110
self.view = GoogleCallbackView.as_view()
111-
111+
112112
self.test_user_data = users_db_data[0]
113113

114114
def test_get_redirects_for_oauth_error(self):
@@ -148,7 +148,7 @@ def test_get_redirects_for_valid_code_and_state(self, mock_create_user, mock_han
148148
"email": self.test_user_data["email_id"],
149149
"name": self.test_user_data["name"],
150150
}
151-
151+
152152
user_id = str(ObjectId())
153153
mock_user = Mock()
154154
mock_user.id = ObjectId(user_id)
@@ -241,8 +241,8 @@ def test_logout_clears_session(self):
241241
def test_logout_clears_sessionid_cookie(self):
242242
"""Test that logout clears sessionid cookie"""
243243
self.client.cookies["sessionid"] = "test_session_id"
244-
244+
245245
response = self.client.post(self.url)
246246

247247
self.assertEqual(response.status_code, status.HTTP_200_OK)
248-
self.assertEqual(response.cookies.get("sessionid").value, "")
248+
self.assertEqual(response.cookies.get("sessionid").value, "")

todo/utils/google_jwt_utils.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ def generate_google_access_token(user_data: dict) -> str:
2828
"token_type": "access",
2929
}
3030

31-
token = jwt.encode(payload=payload, key=settings.GOOGLE_JWT["PRIVATE_KEY"], algorithm=settings.GOOGLE_JWT["ALGORITHM"])
31+
token = jwt.encode(
32+
payload=payload, key=settings.GOOGLE_JWT["PRIVATE_KEY"], algorithm=settings.GOOGLE_JWT["ALGORITHM"]
33+
)
3234
return token
3335

3436
except Exception as e:
@@ -50,7 +52,9 @@ def generate_google_refresh_token(user_data: dict) -> str:
5052
"email": user_data["email"],
5153
"token_type": "refresh",
5254
}
53-
token = jwt.encode(payload=payload, key=settings.GOOGLE_JWT["PRIVATE_KEY"], algorithm=settings.GOOGLE_JWT["ALGORITHM"])
55+
token = jwt.encode(
56+
payload=payload, key=settings.GOOGLE_JWT["PRIVATE_KEY"], algorithm=settings.GOOGLE_JWT["ALGORITHM"]
57+
)
5458

5559
return token
5660

@@ -60,7 +64,9 @@ def generate_google_refresh_token(user_data: dict) -> str:
6064

6165
def validate_google_access_token(token: str) -> dict:
6266
try:
63-
payload = jwt.decode(jwt=token, key=settings.GOOGLE_JWT["PUBLIC_KEY"], algorithms=[settings.GOOGLE_JWT["ALGORITHM"]])
67+
payload = jwt.decode(
68+
jwt=token, key=settings.GOOGLE_JWT["PUBLIC_KEY"], algorithms=[settings.GOOGLE_JWT["ALGORITHM"]]
69+
)
6470

6571
if payload.get("token_type") != "access":
6672
raise GoogleTokenInvalidError(AuthErrorMessages.GOOGLE_TOKEN_INVALID)
@@ -77,7 +83,9 @@ def validate_google_access_token(token: str) -> dict:
7783

7884
def validate_google_refresh_token(token: str) -> dict:
7985
try:
80-
payload = jwt.decode(jwt=token, key=settings.GOOGLE_JWT["PUBLIC_KEY"], algorithms=[settings.GOOGLE_JWT["ALGORITHM"]])
86+
payload = jwt.decode(
87+
jwt=token, key=settings.GOOGLE_JWT["PUBLIC_KEY"], algorithms=[settings.GOOGLE_JWT["ALGORITHM"]]
88+
)
8189
if payload.get("token_type") != "refresh":
8290
raise GoogleTokenInvalidError(AuthErrorMessages.GOOGLE_TOKEN_INVALID)
8391

todo/views/auth.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from todo.utils.google_jwt_utils import generate_google_token_pair
1212
from todo.constants.messages import AppMessages
1313

14+
1415
class GoogleLoginView(APIView):
1516
@extend_schema(
1617
operation_id="google_login",
@@ -94,7 +95,7 @@ def get(self, request: Request):
9495
code = request.query_params.get("code")
9596
state = request.query_params.get("state")
9697
error = request.query_params.get("error")
97-
98+
9899
if error:
99100
frontend_callback = f"{settings.FRONTEND_URL}/auth/callback"
100101
return HttpResponseRedirect(f"{frontend_callback}?error={error}")
@@ -137,7 +138,6 @@ def get(self, request: Request):
137138
frontend_callback = f"{settings.FRONTEND_URL}/auth/callback"
138139
return HttpResponseRedirect(f"{frontend_callback}?error=auth_failed")
139140

140-
141141
def _get_cookie_config(self):
142142
return {
143143
"path": "/",
@@ -154,6 +154,7 @@ def _set_auth_cookies(self, response, tokens):
154154
"ext-refresh", tokens["refresh_token"], max_age=settings.GOOGLE_JWT["REFRESH_TOKEN_LIFETIME"], **config
155155
)
156156

157+
157158
class GoogleLogoutView(APIView):
158159
@extend_schema(
159160
operation_id="google_logout",
@@ -198,13 +199,15 @@ def post(self, request: Request):
198199

199200
def _handle_logout(self, request: Request):
200201
request.session.flush()
201-
202-
response = Response({
203-
"statusCode": status.HTTP_200_OK,
204-
"message": AppMessages.GOOGLE_LOGOUT_SUCCESS,
205-
"data": {"success": True},
206-
})
207-
202+
203+
response = Response(
204+
{
205+
"statusCode": status.HTTP_200_OK,
206+
"message": AppMessages.GOOGLE_LOGOUT_SUCCESS,
207+
"data": {"success": True},
208+
}
209+
)
210+
208211
self._clear_auth_cookies(response)
209212
return response
210213

@@ -226,7 +229,7 @@ def _clear_auth_cookies(self, response):
226229
response.delete_cookie("ext-refresh", **delete_config)
227230

228231
session_delete_config = {
229-
"path": getattr(settings, 'SESSION_COOKIE_PATH', '/'),
230-
"domain": getattr(settings, 'SESSION_COOKIE_DOMAIN', None),
232+
"path": getattr(settings, "SESSION_COOKIE_PATH", "/"),
233+
"domain": getattr(settings, "SESSION_COOKIE_DOMAIN", None),
231234
}
232235
response.delete_cookie("sessionid", **session_delete_config)

todo_project/settings/base.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -121,11 +121,7 @@
121121
}
122122

123123
# JWT Configuration - Use different settings for tests vs production
124-
TESTING = (
125-
'test' in sys.argv or
126-
'pytest' in sys.modules or
127-
os.getenv('TESTING') == 'True'
128-
)
124+
TESTING = "test" in sys.argv or "pytest" in sys.modules or os.getenv("TESTING") == "True"
129125

130126
if TESTING:
131127
# Test JWT configuration (HS256 - simpler for tests)

0 commit comments

Comments
 (0)