Fastapi refactor update

This commit is contained in:
Carlos-Mesquita
2024-10-01 19:31:01 +01:00
parent f92a803d96
commit 2a032c5aba
132 changed files with 22856 additions and 10309 deletions

View File

@@ -1,9 +1,9 @@
from .authentication import AuthBackend, AuthenticationMiddleware
from .authorization import Authorized, IsAuthenticatedViaBearerToken
__all__ = [
"AuthBackend",
"AuthenticationMiddleware",
"Authorized",
"IsAuthenticatedViaBearerToken"
from .authentication import AuthBackend, AuthenticationMiddleware
from .authorization import Authorized, IsAuthenticatedViaBearerToken
__all__ = [
"AuthBackend",
"AuthenticationMiddleware",
"Authorized",
"IsAuthenticatedViaBearerToken"
]

View File

@@ -1,48 +1,48 @@
import os
from typing import Tuple
import jwt
from jwt import InvalidTokenError
from pydantic import BaseModel, Field
from starlette.authentication import AuthenticationBackend
from starlette.middleware.authentication import (
AuthenticationMiddleware as BaseAuthenticationMiddleware,
)
from starlette.requests import HTTPConnection
class Session(BaseModel):
authenticated: bool = Field(False, description="Is user authenticated?")
class AuthBackend(AuthenticationBackend):
async def authenticate(
self, conn: HTTPConnection
) -> Tuple[bool, Session]:
session = Session()
authorization: str = conn.headers.get("Authorization")
if not authorization:
return False, session
try:
scheme, token = authorization.split(" ")
if scheme.lower() != "bearer":
return False, session
except ValueError:
return False, session
jwt_secret_key = os.getenv("JWT_SECRET_KEY")
if not jwt_secret_key:
return False, session
try:
jwt.decode(token, jwt_secret_key, algorithms=["HS256"])
except InvalidTokenError:
return False, session
session.authenticated = True
return True, session
class AuthenticationMiddleware(BaseAuthenticationMiddleware):
pass
import os
from typing import Tuple
import jwt
from jwt import InvalidTokenError
from pydantic import BaseModel, Field
from starlette.authentication import AuthenticationBackend
from starlette.middleware.authentication import (
AuthenticationMiddleware as BaseAuthenticationMiddleware,
)
from starlette.requests import HTTPConnection
class Session(BaseModel):
authenticated: bool = Field(False, description="Is user authenticated?")
class AuthBackend(AuthenticationBackend):
async def authenticate(
self, conn: HTTPConnection
) -> Tuple[bool, Session]:
session = Session()
authorization: str = conn.headers.get("Authorization")
if not authorization:
return False, session
try:
scheme, token = authorization.split(" ")
if scheme.lower() != "bearer":
return False, session
except ValueError:
return False, session
jwt_secret_key = os.getenv("JWT_SECRET_KEY")
if not jwt_secret_key:
return False, session
try:
jwt.decode(token, jwt_secret_key, algorithms=["HS256"])
except InvalidTokenError:
return False, session
session.authenticated = True
return True, session
class AuthenticationMiddleware(BaseAuthenticationMiddleware):
pass

View File

@@ -1,36 +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
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