Ali2206 commited on
Commit
d4fc942
Β·
verified Β·
1 Parent(s): 8920767

Update core/security.py

Browse files
Files changed (1) hide show
  1. 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 β€” adjust tokenUrl if your API has a prefix like /api
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
- logger.info(f"πŸ” Authentication attempt with token: {token[:15]}...") # Log first part of token
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
- logger.error(f"❌ JWTError while decoding token: {str(e)}")
43
  raise HTTPException(status_code=401, detail="Could not validate token")
44
-
45
- user = await users_collection.find_one({"email": email})
46
- if not user:
47
- logger.error(f"❌ User not found for email: {email}")
48
- raise HTTPException(status_code=404, detail="User not found")
49
-
50
- logger.info(f"βœ… Authenticated user: {user['email']}")
51
- return user
 
 
 
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")