| | from fastapi import Depends, HTTPException, status |
| | from fastapi.security import OAuth2PasswordBearer |
| | from jose import JWTError, jwt |
| | from db.mongodb import get_database |
| | from core.config import settings |
| |
|
| | oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login") |
| |
|
| | async def get_current_user( |
| | token: str = Depends(oauth2_scheme), |
| | db = Depends(get_database) |
| | ): |
| | credentials_exception = HTTPException( |
| | status_code=status.HTTP_401_UNAUTHORIZED, |
| | detail="Could not validate credentials", |
| | headers={"WWW-Authenticate": "Bearer"}, |
| | ) |
| | |
| | try: |
| | |
| | payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm]) |
| | email: str = payload.get("sub") |
| | if email is None: |
| | raise credentials_exception |
| | except JWTError: |
| | raise credentials_exception |
| | |
| | |
| | user = await db["users"].find_one({"email": email}) |
| | if user is None: |
| | raise credentials_exception |
| | |
| | |
| | user["_id"] = str(user["_id"]) |
| | user.pop("password", None) |
| | |
| | return user |