Spaces:
Sleeping
Sleeping
Update core/security.py
Browse files- core/security.py +44 -13
core/security.py
CHANGED
|
@@ -12,9 +12,10 @@ logger = logging.getLogger(__name__)
|
|
| 12 |
|
| 13 |
# OAuth2 setup
|
| 14 |
oauth2_scheme = OAuth2PasswordBearer(
|
| 15 |
-
tokenUrl="/auth/login",
|
| 16 |
scheme_name="JWT"
|
| 17 |
)
|
|
|
|
| 18 |
# Password hashing context
|
| 19 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 20 |
|
|
@@ -30,32 +31,62 @@ def verify_password(plain: str, hashed: str) -> bool:
|
|
| 30 |
def create_access_token(data: dict, expires_delta: timedelta = None):
|
| 31 |
to_encode = data.copy()
|
| 32 |
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
| 33 |
-
to_encode.update({"exp": expire})
|
| 34 |
-
|
|
|
|
|
|
|
| 35 |
|
| 36 |
# Get the current user from the JWT token
|
| 37 |
async def get_current_user(request: Request, token: str = Depends(oauth2_scheme)):
|
| 38 |
-
|
| 39 |
-
|
| 40 |
|
| 41 |
if not token:
|
| 42 |
-
|
| 43 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
try:
|
| 46 |
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 47 |
-
|
| 48 |
|
| 49 |
email = payload.get("sub")
|
| 50 |
if not email:
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
except JWTError as e:
|
| 53 |
-
|
| 54 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
user = await users_collection.find_one({"email": email})
|
| 57 |
if not user:
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
|
| 61 |
return user
|
|
|
|
| 12 |
|
| 13 |
# OAuth2 setup
|
| 14 |
oauth2_scheme = OAuth2PasswordBearer(
|
| 15 |
+
tokenUrl="/auth/login",
|
| 16 |
scheme_name="JWT"
|
| 17 |
)
|
| 18 |
+
|
| 19 |
# Password hashing context
|
| 20 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 21 |
|
|
|
|
| 31 |
def create_access_token(data: dict, expires_delta: timedelta = None):
|
| 32 |
to_encode = data.copy()
|
| 33 |
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
| 34 |
+
to_encode.update({"exp": expire, "iat": datetime.utcnow()})
|
| 35 |
+
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 36 |
+
logger.debug(f"Created JWT for {data.get('sub')}, expires at {expire}")
|
| 37 |
+
return encoded_jwt
|
| 38 |
|
| 39 |
# Get the current user from the JWT token
|
| 40 |
async def get_current_user(request: Request, token: str = Depends(oauth2_scheme)):
|
| 41 |
+
logger.debug(f"Processing token: {token[:10]}...") # Log partial token for security
|
| 42 |
+
logger.debug(f"Request headers: {dict(request.headers)}")
|
| 43 |
|
| 44 |
if not token:
|
| 45 |
+
logger.error("No token provided in Authorization header")
|
| 46 |
+
raise HTTPException(
|
| 47 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 48 |
+
detail="No token provided",
|
| 49 |
+
headers={"WWW-Authenticate": "Bearer"}
|
| 50 |
+
)
|
| 51 |
|
| 52 |
try:
|
| 53 |
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 54 |
+
logger.debug(f"Token payload: {payload}")
|
| 55 |
|
| 56 |
email = payload.get("sub")
|
| 57 |
if not email:
|
| 58 |
+
logger.error("Invalid token: missing subject")
|
| 59 |
+
raise HTTPException(
|
| 60 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 61 |
+
detail="Invalid token: missing subject",
|
| 62 |
+
headers={"WWW-Authenticate": "Bearer"}
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
# Check token expiration explicitly
|
| 66 |
+
exp = payload.get("exp")
|
| 67 |
+
if exp and datetime.utcnow().timestamp() > exp:
|
| 68 |
+
logger.error(f"Token expired for {email}")
|
| 69 |
+
raise HTTPException(
|
| 70 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 71 |
+
detail="Token has expired",
|
| 72 |
+
headers={"WWW-Authenticate": "Bearer"}
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
except JWTError as e:
|
| 76 |
+
logger.error(f"JWT decode error: {str(e)}")
|
| 77 |
+
raise HTTPException(
|
| 78 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 79 |
+
detail=f"Could not validate token: {str(e)}",
|
| 80 |
+
headers={"WWW-Authenticate": "Bearer"}
|
| 81 |
+
)
|
| 82 |
|
| 83 |
user = await users_collection.find_one({"email": email})
|
| 84 |
if not user:
|
| 85 |
+
logger.error(f"User not found for email: {email}")
|
| 86 |
+
raise HTTPException(
|
| 87 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
| 88 |
+
detail="User not found"
|
| 89 |
+
)
|
| 90 |
|
| 91 |
+
logger.info(f"Authenticated user: {user['email']}")
|
| 92 |
return user
|