Files
eventspace/backend/app/auth/dependencies.py
Felipe Cardoso 548880b468 Refactor token handling and introduce token revocation logic
Updated `decode_token` for stricter validation of token claims and explicit error handling. Added utilities for token revocation and verification, improving
2025-02-28 16:57:57 +01:00

41 lines
1.2 KiB
Python

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.auth.security import decode_token
from app.models.user import User
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")
async def get_current_user(
token: str = Depends(oauth2_scheme),
db: AsyncSession = Depends(get_db)
):
try:
payload = decode_token(token) # Use updated decode_token.
user_id: str = payload.sub
token_type: str = payload.type
if user_id is None or token_type != "access":
raise HTTPException(status_code=401, detail="Invalid token type.")
user = await db.get(User, user_id)
if user is None:
raise HTTPException(status_code=401, detail="User not found.")
return user
except JWTError as e:
raise HTTPException(status_code=401, detail=str(e))
async def get_current_active_user(
current_user: User = Depends(get_current_user),
):
if not current_user.is_active:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user