feat(auth): switch signup to OTP verification flow
Replace legacy signup with start/verify/resend endpoints, add OTP-focused mail templates and auth rate limits, and align compose/env/runbook for local self-hosted Supabase OTP behavior.
This commit is contained in:
@@ -78,66 +78,6 @@ class CelerySettings(BaseModel):
|
||||
task_max_retries: int = 3
|
||||
|
||||
|
||||
class WebSettings(BaseModel):
|
||||
server: Literal["uvicorn", "gunicorn"] = "gunicorn"
|
||||
host: str = "0.0.0.0"
|
||||
port: int = Field(default=8000, ge=1, le=65535)
|
||||
reload: bool = False
|
||||
workers: int = Field(default=2, ge=1, le=64)
|
||||
worker_class: str = "uvicorn.workers.UvicornWorker"
|
||||
timeout: int = Field(default=60, ge=1, le=600)
|
||||
keepalive: int = Field(default=5, ge=1, le=120)
|
||||
log_level: Literal["debug", "info", "warning", "error", "critical"] = "info"
|
||||
|
||||
|
||||
class GunicornSettings(BaseModel):
|
||||
enabled_in_prod: bool = True
|
||||
workers: int = 2
|
||||
worker_class: str = "uvicorn.workers.UvicornWorker"
|
||||
worker_connections: int = 1000
|
||||
timeout: int = 60
|
||||
graceful_timeout: int = 30
|
||||
keepalive: int = 5
|
||||
max_requests: int = 1000
|
||||
max_requests_jitter: int = 50
|
||||
preload_app: bool = False
|
||||
|
||||
|
||||
class WorkerGroupSettings(BaseModel):
|
||||
concurrency: int = Field(default=2, ge=1, le=32)
|
||||
pool: Literal["prefork", "threads", "solo", "eventlet", "gevent"] = "prefork"
|
||||
time_limit: int = Field(default=300, ge=1, le=7200)
|
||||
soft_time_limit: int = Field(default=240, ge=1, le=3600)
|
||||
max_tasks_per_child: int = Field(default=200, ge=1, le=1000)
|
||||
prefetch_multiplier: int = Field(default=1, ge=1, le=10)
|
||||
|
||||
|
||||
class WorkerSettings(BaseModel):
|
||||
groups: dict[str, WorkerGroupSettings] = Field(
|
||||
default_factory=lambda: {
|
||||
"critical": WorkerGroupSettings(
|
||||
concurrency=2,
|
||||
prefetch_multiplier=1,
|
||||
time_limit=300,
|
||||
),
|
||||
"default": WorkerGroupSettings(
|
||||
concurrency=2,
|
||||
prefetch_multiplier=4,
|
||||
time_limit=600,
|
||||
),
|
||||
"bulk": WorkerGroupSettings(
|
||||
concurrency=1,
|
||||
prefetch_multiplier=1,
|
||||
time_limit=3600,
|
||||
max_tasks_per_child=100,
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
def get_group_config(self, group_name: str) -> WorkerGroupSettings:
|
||||
return self.groups.get(group_name, WorkerGroupSettings())
|
||||
|
||||
|
||||
class CorsSettings(BaseModel):
|
||||
allow_origins: list[str] = Field(
|
||||
default_factory=lambda: [
|
||||
@@ -220,14 +160,11 @@ def _resolve_env_file() -> str:
|
||||
|
||||
class Settings(BaseSettings):
|
||||
runtime: RuntimeSettings = RuntimeSettings()
|
||||
web: WebSettings = WebSettings()
|
||||
gunicorn: GunicornSettings = GunicornSettings()
|
||||
cors: CorsSettings = CorsSettings()
|
||||
redis: RedisSettings = RedisSettings()
|
||||
supabase: SupabaseSettings = SupabaseSettings()
|
||||
celery: CelerySettings = CelerySettings()
|
||||
database: DatabaseSettings = DatabaseSettings()
|
||||
worker: WorkerSettings = WorkerSettings()
|
||||
|
||||
@computed_field
|
||||
@property
|
||||
|
||||
@@ -9,12 +9,16 @@ from supabase import AuthError, create_client
|
||||
from core.config.settings import SupabaseSettings, config
|
||||
from core.logging import get_logger
|
||||
from v1.auth.schemas import (
|
||||
AuthResendCodeResponse,
|
||||
AuthSignupStartResponse,
|
||||
AuthTokenResponse,
|
||||
AuthUser,
|
||||
AuthUserByEmailResponse,
|
||||
LoginRequest,
|
||||
RefreshRequest,
|
||||
SignupRequest,
|
||||
SignupResendRequest,
|
||||
SignupStartRequest,
|
||||
SignupVerifyRequest,
|
||||
)
|
||||
from v1.auth.service import AuthServiceGateway
|
||||
|
||||
@@ -30,22 +34,53 @@ class SupabaseAuthGateway(AuthServiceGateway):
|
||||
self._client = create_client(settings.url, settings.anon_key)
|
||||
self._admin_client = create_client(settings.url, settings.service_role_key)
|
||||
|
||||
async def signup(self, request: SignupRequest) -> AuthTokenResponse:
|
||||
async def signup_start(
|
||||
self, request: SignupStartRequest
|
||||
) -> AuthSignupStartResponse:
|
||||
payload: dict[str, Any] = {
|
||||
"email": request.email,
|
||||
"password": request.password,
|
||||
"data": {"username": request.username},
|
||||
}
|
||||
if request.redirect_to:
|
||||
payload["options"] = {"email_redirect_to": request.redirect_to}
|
||||
try:
|
||||
sign_up = cast(Any, self._client.auth.sign_up)
|
||||
response = await asyncio.to_thread(sign_up, payload)
|
||||
return _map_auth_response(response, "Authentication failed")
|
||||
await asyncio.to_thread(sign_up, payload)
|
||||
return AuthSignupStartResponse(email=request.email)
|
||||
except AuthError as exc:
|
||||
logger.warning("Signup failed", error_type=type(exc).__name__)
|
||||
raise HTTPException(
|
||||
status_code=401, detail="Authentication failed"
|
||||
status_code=422, detail="Invalid signup request"
|
||||
) from exc
|
||||
|
||||
async def signup_verify(self, request: SignupVerifyRequest) -> AuthTokenResponse:
|
||||
payload: dict[str, Any] = {
|
||||
"type": "signup",
|
||||
"email": request.email,
|
||||
"token": request.token,
|
||||
}
|
||||
try:
|
||||
verify_otp = cast(Any, self._client.auth.verify_otp)
|
||||
response = await asyncio.to_thread(verify_otp, payload)
|
||||
return _map_auth_response(response, "Invalid verification code")
|
||||
except AuthError as exc:
|
||||
logger.warning("Signup verify failed", error_type=type(exc).__name__)
|
||||
raise HTTPException(
|
||||
status_code=401, detail="Invalid verification code"
|
||||
) from exc
|
||||
|
||||
async def signup_resend(
|
||||
self, request: SignupResendRequest
|
||||
) -> AuthResendCodeResponse:
|
||||
payload: dict[str, Any] = {"type": "signup", "email": request.email}
|
||||
try:
|
||||
resend = cast(Any, self._client.auth.resend)
|
||||
await asyncio.to_thread(resend, payload)
|
||||
except AuthError as exc:
|
||||
logger.warning("Signup resend failed", error_type=type(exc).__name__)
|
||||
return AuthResendCodeResponse()
|
||||
|
||||
async def login(self, request: LoginRequest) -> AuthTokenResponse:
|
||||
payload: dict[str, Any] = {"email": request.email, "password": request.password}
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from threading import Lock
|
||||
from time import monotonic
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
_BUCKETS: dict[str, deque[float]] = {}
|
||||
_LOCK = Lock()
|
||||
|
||||
|
||||
async def enforce_rate_limit(
|
||||
*,
|
||||
scope: str,
|
||||
identifier: str,
|
||||
limit: int,
|
||||
window_seconds: int,
|
||||
) -> None:
|
||||
_enforce_rate_limit_in_memory(
|
||||
key=f"auth:rate_limit:{scope}:{identifier.lower()}",
|
||||
limit=limit,
|
||||
window_seconds=window_seconds,
|
||||
)
|
||||
|
||||
|
||||
def _enforce_rate_limit_in_memory(
|
||||
*,
|
||||
key: str,
|
||||
limit: int,
|
||||
window_seconds: int,
|
||||
) -> None:
|
||||
now = monotonic()
|
||||
with _LOCK:
|
||||
bucket = _BUCKETS.setdefault(key, deque())
|
||||
cutoff = now - float(window_seconds)
|
||||
while bucket and bucket[0] <= cutoff:
|
||||
bucket.popleft()
|
||||
if len(bucket) >= limit:
|
||||
raise HTTPException(status_code=429, detail="Too many requests")
|
||||
bucket.append(now)
|
||||
|
||||
|
||||
def reset_rate_limit_state() -> None:
|
||||
with _LOCK:
|
||||
_BUCKETS.clear()
|
||||
@@ -6,15 +6,20 @@ from fastapi import APIRouter, Depends, Response
|
||||
from fastapi import HTTPException
|
||||
|
||||
from core.auth.models import CurrentUser
|
||||
from v1.auth.rate_limit import enforce_rate_limit
|
||||
from v1.auth.dependencies import get_auth_service
|
||||
from v1.profile.dependencies import get_current_user
|
||||
from v1.auth.schemas import (
|
||||
AuthResendCodeResponse,
|
||||
AuthSignupStartResponse,
|
||||
AuthTokenResponse,
|
||||
AuthUserByEmailResponse,
|
||||
LoginRequest,
|
||||
LogoutRequest,
|
||||
RefreshRequest,
|
||||
SignupRequest,
|
||||
SignupResendRequest,
|
||||
SignupStartRequest,
|
||||
SignupVerifyRequest,
|
||||
)
|
||||
from v1.auth.service import AuthService
|
||||
|
||||
@@ -22,12 +27,46 @@ from v1.auth.service import AuthService
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/signup", response_model=AuthTokenResponse)
|
||||
async def signup(
|
||||
payload: SignupRequest,
|
||||
@router.post("/signup/start", response_model=AuthSignupStartResponse, status_code=202)
|
||||
async def signup_start(
|
||||
payload: SignupStartRequest,
|
||||
service: AuthService = Depends(get_auth_service),
|
||||
) -> AuthSignupStartResponse:
|
||||
await enforce_rate_limit(
|
||||
scope="signup_start",
|
||||
identifier=payload.email,
|
||||
limit=5,
|
||||
window_seconds=60,
|
||||
)
|
||||
return await service.signup_start(payload)
|
||||
|
||||
|
||||
@router.post("/signup/verify", response_model=AuthTokenResponse)
|
||||
async def signup_verify(
|
||||
payload: SignupVerifyRequest,
|
||||
service: AuthService = Depends(get_auth_service),
|
||||
) -> AuthTokenResponse:
|
||||
return await service.signup(payload)
|
||||
await enforce_rate_limit(
|
||||
scope="signup_verify",
|
||||
identifier=payload.email,
|
||||
limit=10,
|
||||
window_seconds=600,
|
||||
)
|
||||
return await service.signup_verify(payload)
|
||||
|
||||
|
||||
@router.post("/signup/resend", response_model=AuthResendCodeResponse)
|
||||
async def signup_resend(
|
||||
payload: SignupResendRequest,
|
||||
service: AuthService = Depends(get_auth_service),
|
||||
) -> AuthResendCodeResponse:
|
||||
await enforce_rate_limit(
|
||||
scope="signup_resend",
|
||||
identifier=payload.email,
|
||||
limit=3,
|
||||
window_seconds=60,
|
||||
)
|
||||
return await service.signup_resend(payload)
|
||||
|
||||
|
||||
@router.post("/login", response_model=AuthTokenResponse)
|
||||
|
||||
@@ -5,13 +5,22 @@ from typing import Literal
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
|
||||
|
||||
class SignupRequest(BaseModel):
|
||||
class SignupStartRequest(BaseModel):
|
||||
username: str = Field(min_length=3, max_length=30)
|
||||
email: EmailStr
|
||||
password: str = Field(min_length=6)
|
||||
redirect_to: str | None = None
|
||||
|
||||
|
||||
class SignupVerifyRequest(BaseModel):
|
||||
email: EmailStr
|
||||
token: str = Field(pattern=r"^\d{6}$")
|
||||
|
||||
|
||||
class SignupResendRequest(BaseModel):
|
||||
email: EmailStr
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: EmailStr
|
||||
password: str = Field(min_length=6)
|
||||
@@ -45,10 +54,14 @@ class AuthUserByEmailResponse(BaseModel):
|
||||
email_confirmed_at: str | None = None
|
||||
|
||||
|
||||
class SignupPendingResponse(BaseModel):
|
||||
class AuthSignupStartResponse(BaseModel):
|
||||
status: Literal["pending_verification"] = "pending_verification"
|
||||
user: AuthUser
|
||||
message: str = "Email confirmation required"
|
||||
email: EmailStr
|
||||
message: str = "Verification code sent"
|
||||
|
||||
|
||||
class AuthResendCodeResponse(BaseModel):
|
||||
message: str = "If the email exists, a verification code has been sent"
|
||||
|
||||
|
||||
class PasswordResetRequest(BaseModel):
|
||||
|
||||
@@ -3,16 +3,30 @@ from __future__ import annotations
|
||||
from typing import Protocol
|
||||
|
||||
from v1.auth.schemas import (
|
||||
AuthResendCodeResponse,
|
||||
AuthSignupStartResponse,
|
||||
AuthTokenResponse,
|
||||
AuthUserByEmailResponse,
|
||||
LoginRequest,
|
||||
RefreshRequest,
|
||||
SignupRequest,
|
||||
SignupResendRequest,
|
||||
SignupStartRequest,
|
||||
SignupVerifyRequest,
|
||||
)
|
||||
|
||||
|
||||
class AuthServiceGateway(Protocol):
|
||||
async def signup(self, request: SignupRequest) -> AuthTokenResponse:
|
||||
async def signup_start(
|
||||
self, request: SignupStartRequest
|
||||
) -> AuthSignupStartResponse:
|
||||
raise NotImplementedError
|
||||
|
||||
async def signup_verify(self, request: SignupVerifyRequest) -> AuthTokenResponse:
|
||||
raise NotImplementedError
|
||||
|
||||
async def signup_resend(
|
||||
self, request: SignupResendRequest
|
||||
) -> AuthResendCodeResponse:
|
||||
raise NotImplementedError
|
||||
|
||||
async def login(self, request: LoginRequest) -> AuthTokenResponse:
|
||||
@@ -34,8 +48,18 @@ class AuthService:
|
||||
def __init__(self, gateway: AuthServiceGateway) -> None:
|
||||
self._gateway = gateway
|
||||
|
||||
async def signup(self, request: SignupRequest) -> AuthTokenResponse:
|
||||
return await self._gateway.signup(request)
|
||||
async def signup_start(
|
||||
self, request: SignupStartRequest
|
||||
) -> AuthSignupStartResponse:
|
||||
return await self._gateway.signup_start(request)
|
||||
|
||||
async def signup_verify(self, request: SignupVerifyRequest) -> AuthTokenResponse:
|
||||
return await self._gateway.signup_verify(request)
|
||||
|
||||
async def signup_resend(
|
||||
self, request: SignupResendRequest
|
||||
) -> AuthResendCodeResponse:
|
||||
return await self._gateway.signup_resend(request)
|
||||
|
||||
async def login(self, request: LoginRequest) -> AuthTokenResponse:
|
||||
return await self._gateway.login(request)
|
||||
|
||||
Reference in New Issue
Block a user