Async release
This commit is contained in:
36
app/middlewares/authorization.py
Normal file
36
app/middlewares/authorization.py
Normal file
@@ -0,0 +1,36 @@
|
||||
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 app.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
|
||||
Reference in New Issue
Block a user