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:
qzl
2026-02-25 13:34:02 +08:00
parent 02e5e52e1f
commit 1cc8fa1abf
16 changed files with 707 additions and 112 deletions
-63
View File
@@ -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
+40 -5
View File
@@ -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:
+46
View File
@@ -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()
+44 -5
View File
@@ -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)
+17 -4
View File
@@ -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):
+28 -4
View File
@@ -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)
+31 -5
View File
@@ -11,11 +11,15 @@ import uvicorn
from app import app
from v1.auth.dependencies import get_auth_service
from v1.auth.schemas import (
AuthResendCodeResponse,
AuthSignupStartResponse,
AuthTokenResponse,
AuthUser,
LoginRequest,
RefreshRequest,
SignupRequest,
SignupResendRequest,
SignupStartRequest,
SignupVerifyRequest,
)
from v1.auth.service import AuthService
@@ -24,7 +28,12 @@ class FakeE2EAuthService(AuthService):
def __init__(self) -> None:
self._user = AuthUser(id="user-1", email="user@example.com")
async def signup(self, request: SignupRequest) -> AuthTokenResponse:
async def signup_start(
self, request: SignupStartRequest
) -> AuthSignupStartResponse:
return AuthSignupStartResponse(email=request.email)
async def signup_verify(self, request: SignupVerifyRequest) -> AuthTokenResponse:
return AuthTokenResponse(
access_token="access-1",
refresh_token="refresh-1",
@@ -33,6 +42,11 @@ class FakeE2EAuthService(AuthService):
user=self._user,
)
async def signup_resend(
self, request: SignupResendRequest
) -> AuthResendCodeResponse:
return AuthResendCodeResponse()
async def login(self, request: LoginRequest) -> AuthTokenResponse:
return AuthTokenResponse(
access_token="access-2",
@@ -93,7 +107,7 @@ def test_auth_flow_e2e() -> None:
)
try:
signup = request_context.post(
"/api/v1/auth/signup",
"/api/v1/auth/signup/start",
data=json.dumps(
{
"username": "demo",
@@ -103,8 +117,20 @@ def test_auth_flow_e2e() -> None:
),
headers={"Content-Type": "application/json"},
)
assert signup.status == 200
assert signup.json()["access_token"] == "access-1"
assert signup.status == 202
verify = request_context.post(
"/api/v1/auth/signup/verify",
data=json.dumps(
{
"email": "user@example.com",
"token": "123456",
}
),
headers={"Content-Type": "application/json"},
)
assert verify.status == 200
assert verify.json()["access_token"] == "access-1"
login = request_context.post(
"/api/v1/auth/login",
+254 -8
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
from typing import Callable
from uuid import UUID
import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient
@@ -10,24 +11,48 @@ from app import app
from core.auth.models import CurrentUser
from v1.auth.dependencies import get_auth_service
from v1.profile.dependencies import get_current_user
from v1.auth.rate_limit import reset_rate_limit_state
from v1.auth.schemas import (
AuthResendCodeResponse,
AuthSignupStartResponse,
AuthTokenResponse,
AuthUserByEmailResponse,
AuthUser,
LoginRequest,
RefreshRequest,
SignupRequest,
SignupResendRequest,
SignupStartRequest,
SignupVerifyRequest,
)
from v1.auth.service import AuthService
@pytest.fixture(autouse=True)
def reset_auth_rate_limit_state() -> None:
reset_rate_limit_state()
class FakeAuthService(AuthService):
def __init__(self, token_response: AuthTokenResponse) -> None:
self._token_response = token_response
async def signup(self, request: SignupRequest) -> AuthTokenResponse:
async def signup_start(
self, request: SignupStartRequest
) -> AuthSignupStartResponse:
if request.email == "exists@example.com":
raise HTTPException(status_code=422, detail="Invalid signup request")
return AuthSignupStartResponse(email=request.email)
async def signup_verify(self, request: SignupVerifyRequest) -> AuthTokenResponse:
if request.token == "000000":
raise HTTPException(status_code=401, detail="Invalid verification code")
return self._token_response
async def signup_resend(
self, request: SignupResendRequest
) -> AuthResendCodeResponse:
return AuthResendCodeResponse()
async def login(self, request: LoginRequest) -> AuthTokenResponse:
raise HTTPException(status_code=401, detail="Invalid credentials")
@@ -55,7 +80,7 @@ def _override_auth_service(service: AuthService) -> Callable[[], AuthService]:
return _get_service
def test_signup_returns_token_response() -> None:
def test_signup_start_returns_pending_response() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
access_token="access",
@@ -71,13 +96,40 @@ def test_signup_returns_token_response() -> None:
client = TestClient(app)
try:
response = client.post(
"/api/v1/auth/signup",
"/api/v1/auth/signup/start",
json={
"username": "demo",
"email": "user@example.com",
"password": "secret123",
},
)
assert response.status_code == 202
body = response.json()
assert body["status"] == "pending_verification"
assert body["email"] == "user@example.com"
finally:
app.dependency_overrides = {}
def test_signup_verify_returns_token_response() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
user=user,
)
app.dependency_overrides[get_auth_service] = _override_auth_service(
FakeAuthService(token_response)
)
client = TestClient(app)
try:
response = client.post(
"/api/v1/auth/signup/verify",
json={"email": "user@example.com", "token": "123456"},
)
assert response.status_code == 200
body = response.json()
assert body["access_token"] == "access"
@@ -87,6 +139,200 @@ def test_signup_returns_token_response() -> None:
app.dependency_overrides = {}
def test_signup_resend_returns_generic_message() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
user=user,
)
app.dependency_overrides[get_auth_service] = _override_auth_service(
FakeAuthService(token_response)
)
client = TestClient(app)
try:
response = client.post(
"/api/v1/auth/signup/resend",
json={"email": "user@example.com"},
)
assert response.status_code == 200
body = response.json()
assert (
body["message"] == "If the email exists, a verification code has been sent"
)
finally:
app.dependency_overrides = {}
def test_signup_verify_invalid_token_returns_problem_details() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
user=user,
)
app.dependency_overrides[get_auth_service] = _override_auth_service(
FakeAuthService(token_response)
)
client = TestClient(app)
try:
response = client.post(
"/api/v1/auth/signup/verify",
json={"email": "user@example.com", "token": "000000"},
)
assert response.status_code == 401
assert response.headers["content-type"].startswith("application/problem+json")
body = response.json()
assert body["title"] == "Unauthorized"
assert body["status"] == 401
assert body["detail"] == "Invalid verification code"
finally:
app.dependency_overrides = {}
def test_signup_start_existing_email_returns_problem_details() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
user=user,
)
app.dependency_overrides[get_auth_service] = _override_auth_service(
FakeAuthService(token_response)
)
client = TestClient(app)
try:
response = client.post(
"/api/v1/auth/signup/start",
json={
"username": "demo",
"email": "exists@example.com",
"password": "secret123",
},
)
assert response.status_code == 422
assert response.headers["content-type"].startswith("application/problem+json")
body = response.json()
assert body["title"] == "Unprocessable Content"
assert body["status"] == 422
assert body["detail"] == "Invalid signup request"
finally:
app.dependency_overrides = {}
def test_signup_verify_rate_limited_after_too_many_attempts() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
user=user,
)
app.dependency_overrides[get_auth_service] = _override_auth_service(
FakeAuthService(token_response)
)
client = TestClient(app)
try:
for _ in range(10):
ok = client.post(
"/api/v1/auth/signup/verify",
json={"email": "user@example.com", "token": "123456"},
)
assert ok.status_code == 200
blocked = client.post(
"/api/v1/auth/signup/verify",
json={"email": "user@example.com", "token": "123456"},
)
assert blocked.status_code == 429
assert blocked.headers["content-type"].startswith("application/problem+json")
finally:
app.dependency_overrides = {}
def test_signup_resend_rate_limited_after_too_many_attempts() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
user=user,
)
app.dependency_overrides[get_auth_service] = _override_auth_service(
FakeAuthService(token_response)
)
client = TestClient(app)
try:
for _ in range(3):
ok = client.post(
"/api/v1/auth/signup/resend",
json={"email": "user@example.com"},
)
assert ok.status_code == 200
blocked = client.post(
"/api/v1/auth/signup/resend",
json={"email": "user@example.com"},
)
assert blocked.status_code == 429
assert blocked.headers["content-type"].startswith("application/problem+json")
finally:
app.dependency_overrides = {}
def test_signup_start_rate_limited_after_too_many_attempts() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
user=user,
)
app.dependency_overrides[get_auth_service] = _override_auth_service(
FakeAuthService(token_response)
)
client = TestClient(app)
try:
for _ in range(5):
ok = client.post(
"/api/v1/auth/signup/start",
json={
"username": "demo",
"email": "user@example.com",
"password": "secret123",
},
)
assert ok.status_code == 202
blocked = client.post(
"/api/v1/auth/signup/start",
json={
"username": "demo",
"email": "user@example.com",
"password": "secret123",
},
)
assert blocked.status_code == 429
assert blocked.headers["content-type"].startswith("application/problem+json")
finally:
app.dependency_overrides = {}
def test_login_invalid_returns_problem_details() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
@@ -170,7 +416,7 @@ def test_logout_returns_no_content() -> None:
app.dependency_overrides = {}
def test_signup_validation_error_returns_problem_details() -> None:
def test_signup_start_validation_error_returns_problem_details() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
access_token="access",
@@ -185,7 +431,7 @@ def test_signup_validation_error_returns_problem_details() -> None:
client = TestClient(app)
try:
response = client.post("/api/v1/auth/signup", json={})
response = client.post("/api/v1/auth/signup/start", json={})
assert response.status_code == 422
assert response.headers["content-type"].startswith("application/problem+json")
body = response.json()
@@ -196,7 +442,7 @@ def test_signup_validation_error_returns_problem_details() -> None:
app.dependency_overrides = {}
def test_signup_missing_username_returns_problem_details() -> None:
def test_signup_start_missing_username_returns_problem_details() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
access_token="access",
@@ -212,7 +458,7 @@ def test_signup_missing_username_returns_problem_details() -> None:
client = TestClient(app)
try:
response = client.post(
"/api/v1/auth/signup",
"/api/v1/auth/signup/start",
json={"email": "user@example.com", "password": "secret123"},
)
assert response.status_code == 422
+15 -3
View File
@@ -8,22 +8,34 @@ from v1.auth.schemas import (
AuthUser,
LoginRequest,
RefreshRequest,
SignupRequest,
SignupStartRequest,
SignupVerifyRequest,
SignupResendRequest,
)
def test_signup_requires_valid_email() -> None:
with pytest.raises(ValidationError):
SignupRequest(username="demo", email="not-an-email", password="secret123")
SignupStartRequest(username="demo", email="not-an-email", password="secret123")
def test_signup_requires_username() -> None:
with pytest.raises(ValidationError):
SignupRequest.model_validate(
SignupStartRequest.model_validate(
{"email": "user@example.com", "password": "secret123"}
)
def test_signup_verify_requires_six_digit_token() -> None:
with pytest.raises(ValidationError):
SignupVerifyRequest(email="user@example.com", token="abc123")
def test_signup_resend_requires_valid_email() -> None:
with pytest.raises(ValidationError):
SignupResendRequest(email="invalid")
def test_login_requires_valid_email() -> None:
with pytest.raises(ValidationError):
LoginRequest(email="invalid", password="secret123")
@@ -5,11 +5,15 @@ import pytest
import v1.auth.gateway as auth_gateway_module
from v1.auth.schemas import (
AuthTokenResponse,
AuthResendCodeResponse,
AuthSignupStartResponse,
AuthUserByEmailResponse,
AuthUser,
LoginRequest,
RefreshRequest,
SignupRequest,
SignupResendRequest,
SignupStartRequest,
SignupVerifyRequest,
)
from v1.auth.service import AuthService, AuthServiceGateway
@@ -18,9 +22,19 @@ class FakeGateway(AuthServiceGateway):
def __init__(self, response: AuthTokenResponse) -> None:
self._response = response
async def signup(self, request: SignupRequest) -> AuthTokenResponse:
async def signup_start(
self, request: SignupStartRequest
) -> AuthSignupStartResponse:
return AuthSignupStartResponse(email=request.email)
async def signup_verify(self, request: SignupVerifyRequest) -> AuthTokenResponse:
return self._response
async def signup_resend(
self, request: SignupResendRequest
) -> AuthResendCodeResponse:
return AuthResendCodeResponse()
async def login(self, request: LoginRequest) -> AuthTokenResponse:
return self._response
@@ -51,8 +65,16 @@ async def test_signup_maps_response() -> None:
)
service = AuthService(gateway=FakeGateway(token_response))
result = await service.signup(
SignupRequest(username="demo", email="user@example.com", password="secret123")
start_result = await service.signup_start(
SignupStartRequest(
username="demo", email="user@example.com", password="secret123"
)
)
assert start_result.status == "pending_verification"
assert start_result.email == "user@example.com"
result = await service.signup_verify(
SignupVerifyRequest(email="user@example.com", token="123456")
)
assert result.access_token == "access"
@@ -64,7 +86,17 @@ class LogoutAssertingGateway(AuthServiceGateway):
def __init__(self, expected_refresh_token: str) -> None:
self._expected_refresh_token = expected_refresh_token
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:
@@ -104,6 +136,23 @@ async def test_get_user_by_email_forwards_to_gateway() -> None:
assert result.email == "user@example.com"
@pytest.mark.asyncio
async def test_signup_resend_returns_generic_message() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = AuthTokenResponse(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
user=user,
)
service = AuthService(gateway=FakeGateway(token_response))
result = await service.signup_resend(SignupResendRequest(email="user@example.com"))
assert result.message == "If the email exists, a verification code has been sent"
@pytest.mark.asyncio
async def test_supabase_signup_passes_username_in_metadata(
monkeypatch: pytest.MonkeyPatch,
@@ -126,7 +175,7 @@ async def test_supabase_signup_passes_username_in_metadata(
class _Response:
user = _User()
session = _Session()
session = None
return _Response()
@@ -136,8 +185,8 @@ async def test_supabase_signup_passes_username_in_metadata(
monkeypatch.setattr(auth_gateway_module, "create_client", lambda *_: FakeClient())
gateway = auth_gateway_module.SupabaseAuthGateway()
await gateway.signup(
SignupRequest(
await gateway.signup_start(
SignupStartRequest(
username="demo",
email="user@example.com",
password="secret123",