fix auth lifetime

This commit is contained in:
2024-04-07 21:31:15 +00:00
parent f8f5bf80c1
commit d55e8d1df3
13 changed files with 212 additions and 42 deletions

View File

View File

@@ -0,0 +1,60 @@
from typing import Annotated
from fastapi import Depends, HTTPException, Request, Response, status
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
from fastapi.security import OAuth2
from fastapi.security.utils import get_authorization_scheme_param
from api.application.protocols.jwt import JwtTokenProcessor
from api.domain.user.error import UserIsNotAuthorizedError
from api.infrastructure.dependencies.stub import Stub
class OAuth2PasswordBearerWithCookie(OAuth2):
def __init__(
self,
tokenUrl: str,
scheme_name: str | None = None,
scopes: dict[str, str] | None = None,
auto_error: bool = True,
):
if not scopes:
scopes = {}
flows = OAuthFlowsModel(password={"tokenUrl": tokenUrl, "scopes": scopes})
super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error)
async def __call__(self, request: Request) -> str | None:
authorization: str | None = request.cookies.get("access_token")
scheme, param = get_authorization_scheme_param(authorization)
if authorization is None or scheme.lower() != "bearer":
if self.auto_error:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
else:
return None
print(param)
return param
oauth2_scheme = OAuth2PasswordBearerWithCookie("/auth/login")
async def auth_required(
request: Request,
token: Annotated[
str,
Depends(oauth2_scheme),
],
jwt_processor: Annotated[JwtTokenProcessor, Depends(Stub(JwtTokenProcessor))],
) -> None:
if token is None:
raise UserIsNotAuthorizedError("Invalid authorization credentials")
if jwt_processor.validate_token(token=token) is None:
raise UserIsNotAuthorizedError("authorization credentials is old")
request.scope["auth"] = token

View File

@@ -39,3 +39,13 @@ async def login(
response.set_cookie(key="access_token", value=f"Bearer {token}", httponly=True)
return user
@auth_router.post("/logout")
async def logout(
response: Response,
):
response.delete_cookie(key="access_token", httponly=True)
return {"result": "logout"}

View File

@@ -1,10 +1,15 @@
from fastapi import APIRouter
from fastapi import APIRouter, Depends
from api.application.contracts.user import UserResponse
from api.presentation.auth.fasapi_auth import auth_required
user_router = APIRouter(prefix="/users", tags=["Users"])
@user_router.get("/")
@user_router.get(
"/",
response_model=list[UserResponse],
dependencies=[Depends(auth_required)],
)
async def get_all_users() -> list[UserResponse]:
return []