felicity-lims/felicity/api/rest/deps.py

48 lines
1.5 KiB
Python
Raw Normal View History

2023-04-10 20:23:31 +08:00
from apps.common import schemas
from apps.user import models
from core import security
from core.config import settings
2021-01-06 19:52:14 +08:00
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
2023-03-19 23:21:32 +08:00
from jose import jwt
from pydantic import ValidationError
2021-01-06 19:52:14 +08:00
reusable_oauth2 = OAuth2PasswordBearer(
tokenUrl=f"{settings.API_V1_STR}/login/access-token"
)
2022-01-19 08:40:02 +08:00
async def get_current_user(token: str = Depends(reusable_oauth2)) -> models.User:
2021-01-06 19:52:14 +08:00
try:
payload = jwt.decode(
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
)
token_data = schemas.TokenPayload(**payload)
except (jwt.JWTError, ValidationError):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Could not validate credentials",
)
2022-01-19 08:40:02 +08:00
user = await models.User.get(uid=token_data.sub)
2021-01-06 19:52:14 +08:00
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
2022-11-06 20:09:44 +08:00
def get_current_active_user(
2023-03-19 23:21:32 +08:00
current_user: models.User = Depends(get_current_user),
2022-11-06 20:09:44 +08:00
) -> models.User:
2022-01-19 08:40:02 +08:00
if not current_user.is_active:
2021-01-06 19:52:14 +08:00
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
2022-11-06 20:09:44 +08:00
def get_current_active_superuser(
2023-03-19 23:21:32 +08:00
current_user: models.User = Depends(get_current_user),
2022-11-06 20:09:44 +08:00
) -> models.User:
2022-01-19 08:40:02 +08:00
if not current_user.is_superuser:
2021-01-06 19:52:14 +08:00
raise HTTPException(
status_code=400, detail="The user doesn't have enough privileges"
)
return current_user