|
5 | 5 | import hashlib |
6 | 6 | from hashlib import sha256 |
7 | 7 | import os |
| 8 | +import re |
8 | 9 | from typing import List, Optional |
9 | 10 | from urllib.parse import urlencode |
10 | 11 | import uuid |
@@ -272,34 +273,38 @@ def get_current_active_user( |
272 | 273 | if api_key: |
273 | 274 | user = get_user_by_api_key(api_key) |
274 | 275 | elif token: |
275 | | - try: |
276 | | - # Decode token in Authorization header to get user |
277 | | - payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM]) |
278 | | - user_id = payload.get("id") |
279 | | - |
280 | | - if user_id is None: |
281 | | - print("No user ID found in token") |
| 276 | + # Check if token is an API key |
| 277 | + if re.match(r"^[A-Fa-f0-9]{32}$", token): |
| 278 | + user = get_user_by_api_key(token) |
| 279 | + else: |
| 280 | + try: |
| 281 | + # Decode token in Authorization header to get user |
| 282 | + payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM]) |
| 283 | + user_id = payload.get("id") |
| 284 | + |
| 285 | + if user_id is None: |
| 286 | + print("No user ID found in token") |
| 287 | + raise HTTPException( |
| 288 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 289 | + detail="Invalid token", |
| 290 | + headers={"WWW-Authenticate": "Bearer"}, |
| 291 | + ) |
| 292 | + # Fetch the user by ID from the database |
| 293 | + user = User.objects.get(id=user_id) |
| 294 | + except jwt.ExpiredSignatureError: |
| 295 | + print("Token has expired") |
| 296 | + raise HTTPException( |
| 297 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 298 | + detail="Token has expired", |
| 299 | + headers={"WWW-Authenticate": "Bearer"}, |
| 300 | + ) |
| 301 | + except jwt.InvalidTokenError: |
| 302 | + print("Invalid token") |
282 | 303 | raise HTTPException( |
283 | 304 | status_code=status.HTTP_401_UNAUTHORIZED, |
284 | 305 | detail="Invalid token", |
285 | 306 | headers={"WWW-Authenticate": "Bearer"}, |
286 | 307 | ) |
287 | | - # Fetch the user by ID from the database |
288 | | - user = User.objects.get(id=user_id) |
289 | | - except jwt.ExpiredSignatureError: |
290 | | - print("Token has expired") |
291 | | - raise HTTPException( |
292 | | - status_code=status.HTTP_401_UNAUTHORIZED, |
293 | | - detail="Token has expired", |
294 | | - headers={"WWW-Authenticate": "Bearer"}, |
295 | | - ) |
296 | | - except jwt.InvalidTokenError: |
297 | | - print("Invalid token") |
298 | | - raise HTTPException( |
299 | | - status_code=status.HTTP_401_UNAUTHORIZED, |
300 | | - detail="Invalid token", |
301 | | - headers={"WWW-Authenticate": "Bearer"}, |
302 | | - ) |
303 | 308 | else: |
304 | 309 | raise HTTPException( |
305 | 310 | status_code=status.HTTP_401_UNAUTHORIZED, |
|
0 commit comments