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

45 lines
1.3 KiB
Python

"""OAuth2 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 OAuth2PasswordBearer
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
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="users/login")
async def get_current_user(
token: Annotated[str, Depends(oauth2_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(token, 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)]