Spaces:
Sleeping
Sleeping
Update core/security.py
Browse files- core/security.py +9 -4
core/security.py
CHANGED
|
@@ -5,6 +5,9 @@ from fastapi import Depends, HTTPException, status
|
|
| 5 |
from fastapi.security import OAuth2PasswordBearer
|
| 6 |
from core.config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES
|
| 7 |
from db.mongo import users_collection
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# OAuth2 setup
|
| 10 |
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
|
|
@@ -29,22 +32,24 @@ def create_access_token(data: dict, expires_delta: timedelta = None):
|
|
| 29 |
|
| 30 |
# Get the current user from the JWT token
|
| 31 |
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
| 32 |
-
|
| 33 |
try:
|
| 34 |
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 35 |
email: str = payload.get("sub")
|
| 36 |
if email is None:
|
|
|
|
| 37 |
raise HTTPException(status_code=401, detail="Invalid token: subject missing")
|
| 38 |
except JWTError as e:
|
| 39 |
-
|
| 40 |
raise HTTPException(status_code=401, detail="Could not validate token")
|
| 41 |
|
| 42 |
try:
|
| 43 |
user = await users_collection.find_one({"email": email})
|
| 44 |
if not user:
|
|
|
|
| 45 |
raise HTTPException(status_code=404, detail="User not found")
|
| 46 |
-
|
| 47 |
return user
|
| 48 |
except Exception as e:
|
| 49 |
-
|
| 50 |
raise HTTPException(status_code=500, detail="Database error")
|
|
|
|
| 5 |
from fastapi.security import OAuth2PasswordBearer
|
| 6 |
from core.config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES
|
| 7 |
from db.mongo import users_collection
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
|
| 12 |
# OAuth2 setup
|
| 13 |
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
|
|
|
|
| 32 |
|
| 33 |
# Get the current user from the JWT token
|
| 34 |
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
| 35 |
+
logger.info(f"π Raw token received: {token}")
|
| 36 |
try:
|
| 37 |
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 38 |
email: str = payload.get("sub")
|
| 39 |
if email is None:
|
| 40 |
+
logger.error("Invalid token: subject missing")
|
| 41 |
raise HTTPException(status_code=401, detail="Invalid token: subject missing")
|
| 42 |
except JWTError as e:
|
| 43 |
+
logger.error(f"β JWTError while decoding token: {str(e)}")
|
| 44 |
raise HTTPException(status_code=401, detail="Could not validate token")
|
| 45 |
|
| 46 |
try:
|
| 47 |
user = await users_collection.find_one({"email": email})
|
| 48 |
if not user:
|
| 49 |
+
logger.error(f"User not found: {email}")
|
| 50 |
raise HTTPException(status_code=404, detail="User not found")
|
| 51 |
+
logger.info(f"β
Authenticated user: {user['email']}")
|
| 52 |
return user
|
| 53 |
except Exception as e:
|
| 54 |
+
logger.error(f"β MongoDB error: {str(e)}")
|
| 55 |
raise HTTPException(status_code=500, detail="Database error")
|