37 lines
1.1 KiB
Python
37 lines
1.1 KiB
Python
from abc import ABC, abstractmethod
|
|
from typing import List, Type
|
|
|
|
from fastapi import Request
|
|
from fastapi.openapi.models import APIKey, APIKeyIn
|
|
from fastapi.security.base import SecurityBase
|
|
|
|
from ielts_be.exceptions import CustomException, UnauthorizedException
|
|
|
|
|
|
class BaseAuthorization(ABC):
|
|
exception = CustomException
|
|
|
|
@abstractmethod
|
|
async def has_permission(self, request: Request) -> bool:
|
|
pass
|
|
|
|
|
|
class IsAuthenticatedViaBearerToken(BaseAuthorization):
|
|
exception = UnauthorizedException
|
|
|
|
async def has_permission(self, request: Request) -> bool:
|
|
return request.user.authenticated
|
|
|
|
|
|
class Authorized(SecurityBase):
|
|
def __init__(self, permissions: List[Type[BaseAuthorization]]):
|
|
self.permissions = permissions
|
|
self.model: APIKey = APIKey(**{"in": APIKeyIn.header}, name="Authorization")
|
|
self.scheme_name = self.__class__.__name__
|
|
|
|
async def __call__(self, request: Request):
|
|
for permission in self.permissions:
|
|
cls = permission()
|
|
if not await cls.has_permission(request=request):
|
|
raise cls.exception
|