Spaces:
Running on T4
Running on T4
File size: 2,777 Bytes
2756f0f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | """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)
|