Spaces:
Sleeping
Sleeping
Update core/security.py
Browse files- core/security.py +14 -15
core/security.py
CHANGED
|
@@ -6,10 +6,9 @@ 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")
|
| 11 |
|
| 12 |
-
|
| 13 |
# Password hashing context
|
| 14 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 15 |
|
|
@@ -28,24 +27,24 @@ def create_access_token(data: dict, expires_delta: timedelta = None):
|
|
| 28 |
to_encode.update({"exp": expire})
|
| 29 |
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 30 |
|
|
|
|
| 31 |
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
| 32 |
-
|
| 33 |
-
|
| 34 |
try:
|
| 35 |
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 36 |
-
logger.info(f"π Token payload: {payload}")
|
| 37 |
email: str = payload.get("sub")
|
| 38 |
if email is None:
|
| 39 |
-
logger.error("β Invalid token: subject missing")
|
| 40 |
raise HTTPException(status_code=401, detail="Invalid token: subject missing")
|
| 41 |
except JWTError as e:
|
| 42 |
-
|
| 43 |
raise HTTPException(status_code=401, detail="Could not validate token")
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
| 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")
|
| 11 |
|
|
|
|
| 12 |
# Password hashing context
|
| 13 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 14 |
|
|
|
|
| 27 |
to_encode.update({"exp": expire})
|
| 28 |
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 29 |
|
| 30 |
+
# Get the current user from the JWT token
|
| 31 |
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
| 32 |
+
print("π Raw token received:", token)
|
|
|
|
| 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 |
+
print("β JWTError while decoding token:", str(e))
|
| 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 |
+
print("β
Authenticated user:", user["email"])
|
| 47 |
+
return user
|
| 48 |
+
except Exception as e:
|
| 49 |
+
print("β MongoDB error:", str(e))
|
| 50 |
+
raise HTTPException(status_code=500, detail="Database error")
|