baseball-engine / backend /app /modules /auth /controller.py
github-actions[bot]
Automated Deploy: 0d5b759d8eca219a25b3ab717925e73a66bbf4a4
2756f0f
Raw History Blame Contribute Delete
2.78 kB
"""A1-A7: register, login, social sign-in, refresh, logout and the password reset flow."""
from typing import Annotated
from fastapi import APIRouter, BackgroundTasks, Depends, Request, Response
from app.core.dependencies import CurrentAccount, Db
from app.core.rate_limit import RateLimiter, get_rate_limiter
from app.integrations.email import EmailClient, get_email_client
from app.integrations.social_auth import SocialTokenVerifier, get_social_verifier
from app.modules.auth.schemas import (
AuthOut,
ForgotPasswordIn,
LoginIn,
RefreshIn,
RegisterIn,
ResetPasswordIn,
SocialAuthOut,
SocialIn,
TokensOut,
)
from app.modules.auth.service import AuthService
router = APIRouter(prefix="/v1", tags=["auth"])
def get_auth_service(
db: Db,
limiter: Annotated[RateLimiter, Depends(get_rate_limiter)],
email: Annotated[EmailClient, Depends(get_email_client)],
verifier: Annotated[SocialTokenVerifier, Depends(get_social_verifier)],
) -> AuthService:
return AuthService(db, limiter, email, verifier)
Auth = Annotated[AuthService, Depends(get_auth_service)]
def _client_ip(request: Request) -> str:
return request.client.host if request.client else "unknown"
@router.post("/auth/register", status_code=201, response_model=AuthOut)
async def register(body: RegisterIn, auth: Auth) -> AuthOut:
return await auth.register(body.email, body.password, body.role)
@router.post("/auth/login", response_model=AuthOut)
async def login(body: LoginIn, request: Request, auth: Auth) -> AuthOut:
return await auth.login(body.email, body.password, _client_ip(request))
@router.post("/auth/social", response_model=SocialAuthOut)
async def social(body: SocialIn, auth: Auth) -> SocialAuthOut:
return await auth.social(body.provider, body.id_token, body.role)
@router.post("/auth/refresh", response_model=TokensOut)
async def refresh(body: RefreshIn, auth: Auth) -> TokensOut:
return await auth.refresh(body.refresh_token)
@router.post("/auth/logout", status_code=204)
async def logout(body: RefreshIn, account: CurrentAccount, auth: Auth) -> Response:
await auth.logout(account, body.refresh_token)
return Response(status_code=204)
@router.post("/auth/password/forgot", status_code=202)
async def forgot_password(body: ForgotPasswordIn, request: Request, auth: Auth, tasks: BackgroundTasks) -> Response:
send_email = await auth.forgot_password(body.email, _client_ip(request))
if send_email:
tasks.add_task(send_email)
return Response(status_code=202)
@router.post("/auth/password/reset", status_code=204)
async def reset_password(body: ResetPasswordIn, auth: Auth) -> Response:
await auth.reset_password(body.token, body.password)
return Response(status_code=204)