Spaces:
Sleeping
Sleeping
| from config.constant import SecurityConstants | |
| from externals.databases.pg_crud import get_user_by_id | |
| from externals.databases.database import get_db | |
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import OAuth2PasswordBearer | |
| from jose import jwt, JWTError | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/admin/login") | |
| async def get_current_user( | |
| token: str = Depends(oauth2_scheme), | |
| db: AsyncSession = Depends(get_db), | |
| ): | |
| credentials_exception = HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Could not validate credentials", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| try: | |
| payload = jwt.decode( | |
| token, | |
| SecurityConstants.JWT_SECRET_KEY, | |
| algorithms=[SecurityConstants.JWT_ALGORITHM], | |
| ) | |
| user_id: str | None = payload.get("sub") | |
| if user_id is None: | |
| raise credentials_exception | |
| except JWTError: | |
| raise credentials_exception | |
| user = await get_user_by_id(db, user_id) | |
| if not user: | |
| raise credentials_exception | |
| return user |