lavkach3
56 строк · 2.0 Кб
1from typing import Optional, Tuple2from uuid import uuid43
4import jwt5from starlette.authentication import AuthenticationBackend6from starlette.middleware.authentication import (7AuthenticationMiddleware as BaseAuthenticationMiddleware,8)
9from starlette.requests import HTTPConnection10
11from core.db_config import config12from core.service_config import config as app_config13from ..schemas import CurrentUser14
15
16class AuthBackend(AuthenticationBackend):17async def authenticate(self, conn: HTTPConnection) -> Tuple[bool, Optional[CurrentUser]]:18current_user = CurrentUser()19authorization: str = conn.headers.get("Authorization") or conn.cookies.get('token')20if not authorization:21return False, current_user22if app_config.INTERCO_TOKEN in authorization:23current_user = CurrentUser(user_id=uuid4(), is_admin=True)24return True, current_user25try:26payload = jwt.decode(27authorization,28config.JWT_SECRET_KEY,29algorithms=[config.JWT_ALGORITHM],30)31current_user = CurrentUser(**payload)32except jwt.exceptions.PyJWTError:33return False, current_user34return True, current_user35class AuthBffBackend(AuthenticationBackend):36async def authenticate(self, conn: HTTPConnection) -> Tuple[bool, Optional[CurrentUser]]:37current_user = CurrentUser()38authorization: str = conn.headers.get("Authorization") or conn.cookies.get('token')39if not authorization:40return False, current_user41if not authorization:42return False, current_user43try:44payload = jwt.decode(45authorization,46config.JWT_SECRET_KEY,47algorithms=[config.JWT_ALGORITHM],48)49current_user = CurrentUser(**payload)50except jwt.exceptions.PyJWTError:51return False, current_user52return True, current_user53
54
55class AuthenticationMiddleware(BaseAuthenticationMiddleware):56pass57