51 lines
1.7 KiB
Python
51 lines
1.7 KiB
Python
from typing import Annotated
|
|
|
|
from fastapi import APIRouter, Depends, Response
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
|
|
from api.application.contracts.auth import LoginRequest, UserCreateRequest
|
|
from api.application.contracts.auth.auth_response import AuthenticationResponse
|
|
from api.application.protocols.jwt import JwtTokenProcessor
|
|
from api.application.usecase.auth.auth_user import LoginUser
|
|
from api.application.usecase.auth.create_user import CreateUser
|
|
from api.domain.user.model import UserEmail, UserId
|
|
from api.infrastructure.dependencies.stub import Stub
|
|
|
|
auth_router = APIRouter(prefix="/auth", tags=["Auth"])
|
|
|
|
|
|
@auth_router.post("/register", status_code=201)
|
|
async def create_user(
|
|
request: UserCreateRequest,
|
|
usecase: Annotated[CreateUser, Depends(Stub(CreateUser))],
|
|
) -> None:
|
|
return await usecase.execute(request)
|
|
|
|
|
|
@auth_router.post("/login", response_model=AuthenticationResponse)
|
|
async def login(
|
|
response: Response,
|
|
login_request: Annotated[OAuth2PasswordRequestForm, Depends()],
|
|
login_interactor: Annotated[LoginUser, Depends(Stub(LoginUser))],
|
|
token_processor: Annotated[JwtTokenProcessor, Depends(Stub(JwtTokenProcessor))],
|
|
) -> AuthenticationResponse:
|
|
user = await login_interactor(
|
|
LoginRequest(
|
|
email=login_request.username,
|
|
password=login_request.password,
|
|
)
|
|
)
|
|
token = token_processor.generate_token(UserId(user.id), UserEmail(user.email))
|
|
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"}
|