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
+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",