HR-ATS-Portal/backend/users/permissions.py

46 lines
1.4 KiB
Python

"""HTTP Bearer scheme and the current-user dependency for `/users/*` routes."""
from __future__ import annotations
from typing import Annotated
import jwt
from fastapi import Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from db_setup import get_session
from users.models import Users
from users.plugins import decode_token
from users.serializers import serialize_user
bearer_scheme = HTTPBearer()
async def get_current_user(
credentials: Annotated[HTTPAuthorizationCredentials, Depends(bearer_scheme)],
session: Annotated[AsyncSession, Depends(get_session)],
) -> dict:
credentials_exception = HTTPException(
status_code=401,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = decode_token(credentials.credentials, expected_type="access")
except jwt.PyJWTError:
raise credentials_exception
user = await Users.get_user_by_id(session, payload.get("sub"))
if not user or user.is_deleted or not user.is_active:
raise HTTPException(
status_code=401,
detail="User is inactive or does not exist",
headers={"WWW-Authenticate": "Bearer"},
)
return serialize_user(user)
CurrentUser = Annotated[dict, Depends(get_current_user)]