AIDA / app /guards /jwt_guard.py
destinyebuka's picture
fyp
cbe6884
from fastapi import HTTPException, status, Depends
from fastapi.security import HTTPBearer
import logging
from app.core.security import verify_access_token
from app.services.token_blacklist_service import token_blacklist_service
logger = logging.getLogger(__name__)
security = HTTPBearer()
async def get_current_user(credentials = Depends(security)) -> dict:
"""
Dependency for protected routes
Validates JWT token and returns user data.
Also checks if token has been blacklisted (logged out).
"""
token = credentials.credentials
payload = verify_access_token(token)
if not payload:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
headers={"WWW-Authenticate": "Bearer"},
)
# Check if token is blacklisted (user logged out)
jti = payload.get("jti")
if jti:
is_blacklisted = await token_blacklist_service.is_blacklisted(jti)
if is_blacklisted:
logger.info(f"🚫 Rejected blacklisted token for user: {payload.get('user_id')}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has been revoked. Please log in again.",
headers={"WWW-Authenticate": "Bearer"},
)
return payload