chat_back/app/users/dependencies.py

48 lines
1.5 KiB
Python

from datetime import datetime
from fastapi import Depends, Request, Response
from jose import JWTError, jwt
from app.config import settings
from app.exceptions import (IncorrectTokenFormatException,
TokenAbsentException, TokenExpiredException,
UserIsNotPresentException, UserMustConfirmEmailException)
from app.services.user_service import UserService
from app.users.auth import create_access_token, VERIFICATED_USER
from app.users.schemas import SUser
def get_token(request: Request) -> str:
token = request.cookies.get("black_phoenix_access_token")
if not token:
raise TokenAbsentException
return token
async def get_current_user(response: Response, token: str = Depends(get_token)) -> SUser:
try:
payload = jwt.decode(token, settings.SECRET_KEY, settings.ALGORITHM)
except JWTError:
raise IncorrectTokenFormatException
expire: str = payload.get("exp")
if not expire or int(expire) < datetime.utcnow().timestamp():
raise TokenExpiredException
user_id: str = payload.get("sub")
if not user_id:
raise UserIsNotPresentException
user = await UserService.find_one_or_none(user_id=int(user_id))
if not user:
raise UserIsNotPresentException
access_token = create_access_token({"sub": user.id})
response.set_cookie(key="black_phoenix_access_token", value=access_token, httponly=True)
return user
async def check_verificated_user_with_exc(user: SUser = Depends(get_current_user)) -> SUser:
if not user.role >= VERIFICATED_USER:
raise UserMustConfirmEmailException
return user