lavkach3
52 строки · 1.5 Кб
1from abc import ABC, abstractmethod2from typing import List, Type3
4from fastapi import Request5from fastapi.openapi.models import APIKey, APIKeyIn6from fastapi.security.base import SecurityBase7
8from core.exceptions import CustomException, UnauthorizedException9
10
11class BasePermission(ABC):12exception = CustomException13
14@abstractmethod15async def has_permission(self, request: Request) -> bool:16pass17
18
19class IsAuthenticated(BasePermission):20exception = UnauthorizedException21
22async def has_permission(self, request: Request) -> bool:23return request.user.user_id is not None24
25
26class IsAdmin(BasePermission):27exception = UnauthorizedException28
29async def has_permission(self, request: Request) -> bool:30user_id = request.user.user_id31if not user_id:32return False33
34return await user_id.is_admin35
36
37class AllowAll(BasePermission):38async def has_permission(self, request: Request) -> bool:39return True40
41
42class PermissionDependency(SecurityBase):43def __init__(self, permissions: List[Type[BasePermission]]):44self.permissions = permissions45self.model: APIKey = APIKey(**{"in": APIKeyIn.header}, name="Authorization")46self.scheme_name = self.__class__.__name__47
48async def __call__(self, request: Request):49for permission in self.permissions:50cls = permission()51if not await cls.has_permission(request=request):52raise cls.exception53