refactor(backend): update API routes and service layer

- Update agent router/service/repository with new endpoints
- Update auth routes with phone-based authentication
- Update users service with new phone lookup
- Update schedule_items with new schemas
- Update message schemas with visibility support
- Update settings with new automation scheduler config
- Update CLI with new commands
- Update tests to match new API contracts
This commit is contained in:
qzl
2026-03-19 18:42:59 +08:00
parent 641d847008
commit f0af44d840
36 changed files with 1083 additions and 1853 deletions
+90 -295
View File
@@ -8,13 +8,9 @@ from fastapi import HTTPException
from v1.auth.gateway import SupabaseAuthGateway
from v1.auth.schemas import (
PasswordResetConfirmRequest,
PasswordResetRequest,
SessionCreateRequest,
OtpSendRequest,
PhoneSessionCreateRequest,
SessionRefreshRequest,
VerificationCreateRequest,
VerificationVerifyRequest,
VerificationResendRequest,
)
@@ -35,314 +31,83 @@ class TestSupabaseAuthGateway:
return SupabaseAuthGateway(), mock_client, mock_admin_client
@pytest.mark.asyncio
async def test_request_password_reset_calls_email_with_string(
async def test_send_otp_sets_should_create_user(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
mock_reset_email = MagicMock()
mock_client.auth.reset_password_email = mock_reset_email
mock_sign_in_with_otp = MagicMock()
mock_client.auth.sign_in_with_otp = mock_sign_in_with_otp
request = PasswordResetRequest(email="test@example.com")
await sut.request_password_reset(request)
await sut.send_otp(OtpSendRequest(phone="+8613812345678"))
mock_reset_email.assert_called_once_with("test@example.com")
@pytest.mark.asyncio
async def test_create_verification_maps_timeout_error_to_503(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
from supabase import AuthError
mock_client.auth.sign_up = MagicMock(
side_effect=AuthError("request_timeout", None)
)
with pytest.raises(HTTPException) as exc_info:
await sut.create_verification(
VerificationCreateRequest(
username="tester",
email="test@example.com",
password="secret123",
)
)
assert exc_info.value.status_code == 503
assert exc_info.value.detail == "Auth service temporarily unavailable"
@pytest.mark.asyncio
async def test_request_password_reset_with_redirect(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
mock_reset_email = MagicMock()
mock_client.auth.reset_password_email = mock_reset_email
request = PasswordResetRequest(
email="test@example.com",
redirect_to="http://localhost:3000/reset-password",
)
await sut.request_password_reset(request)
mock_reset_email.assert_called_once_with(
"test@example.com",
options={"redirect_to": "http://localhost:3000/reset-password"},
)
@pytest.mark.asyncio
async def test_create_verification_rejects_untrusted_redirect_url(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, _, _ = gateway
with pytest.raises(HTTPException) as exc_info:
await sut.create_verification(
VerificationCreateRequest(
username="tester",
email="test@example.com",
password="secret123",
redirect_to="https://evil.example.com/callback",
)
)
assert exc_info.value.status_code == 422
assert exc_info.value.detail == "Invalid redirect URL"
@pytest.mark.asyncio
async def test_request_password_reset_rejects_untrusted_redirect_url(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, _, _ = gateway
with pytest.raises(HTTPException) as exc_info:
await sut.request_password_reset(
PasswordResetRequest(
email="test@example.com",
redirect_to="https://evil.example.com/reset",
)
)
assert exc_info.value.status_code == 422
assert exc_info.value.detail == "Invalid redirect URL"
@pytest.mark.asyncio
async def test_request_password_reset_swallows_auth_error(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
from supabase import AuthError
mock_reset_email = MagicMock(side_effect=AuthError("rate limit exceeded", None))
mock_client.auth.reset_password_email = mock_reset_email
request = PasswordResetRequest(email="test@example.com")
result = await sut.request_password_reset(request)
mock_reset_email.assert_called_once()
assert result is None
@pytest.mark.asyncio
async def test_request_password_reset_extracts_email_from_mapping(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
mock_reset_email = MagicMock()
mock_client.auth.reset_password_email = mock_reset_email
request = PasswordResetRequest.model_construct(
email={"email": "test@example.com"},
redirect_to=None,
)
await sut.request_password_reset(request)
mock_reset_email.assert_called_once_with("test@example.com")
@pytest.mark.asyncio
async def test_request_password_reset_rejects_invalid_email_shape(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, _, _ = gateway
request = PasswordResetRequest.model_construct(
email={"unexpected": "value"},
redirect_to=None,
)
with pytest.raises(HTTPException) as exc_info:
await sut.request_password_reset(request)
assert exc_info.value.status_code == 422
assert exc_info.value.detail == "Invalid email"
@pytest.mark.asyncio
async def test_confirm_password_reset_updates_password_by_user_id(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, mock_admin_client = gateway
verify_response = SimpleNamespace(
session=SimpleNamespace(access_token="access"),
user=SimpleNamespace(id="user-1"),
)
mock_verify_otp = MagicMock(return_value=verify_response)
mock_client.auth.verify_otp = mock_verify_otp
mock_update_user_by_id = MagicMock()
mock_admin_client.auth.admin = SimpleNamespace(
update_user_by_id=mock_update_user_by_id
)
request = PasswordResetConfirmRequest(
email="test@example.com",
token="123456",
new_password="newpassword123",
)
await sut.confirm_password_reset(request)
mock_verify_otp.assert_called_once_with(
mock_sign_in_with_otp.assert_called_once_with(
{
"type": "recovery",
"email": "test@example.com",
"token": "123456",
"phone": "+8613812345678",
"options": {"should_create_user": True},
}
)
mock_update_user_by_id.assert_called_once_with(
"user-1",
{"password": "newpassword123"},
)
@pytest.mark.asyncio
async def test_confirm_password_reset_raises_when_user_id_missing(
async def test_create_phone_session_uses_verify_otp(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
verify_response = SimpleNamespace(
session=SimpleNamespace(access_token="access"),
user=SimpleNamespace(id=""),
session=SimpleNamespace(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
),
user=SimpleNamespace(id="user-1", phone="+8613812345678"),
)
mock_client.auth.verify_otp = MagicMock(return_value=verify_response)
request = PasswordResetConfirmRequest(
email="test@example.com",
token="123456",
new_password="newpassword123",
response = await sut.create_phone_session(
PhoneSessionCreateRequest(phone="+8613812345678", token="123456")
)
assert response.user.id == "user-1"
assert response.access_token == "access"
@pytest.mark.asyncio
async def test_create_phone_session_normalizes_phone_without_plus_prefix(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
verify_response = SimpleNamespace(
session=SimpleNamespace(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
),
user=SimpleNamespace(id="user-1", phone="14155552671"),
)
mock_client.auth.verify_otp = MagicMock(return_value=verify_response)
response = await sut.create_phone_session(
PhoneSessionCreateRequest(phone="+14155552671", token="123456")
)
assert response.user.phone == "+14155552671"
@pytest.mark.asyncio
async def test_refresh_session_maps_invalid_token(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
mock_client.auth.refresh_session = MagicMock(
return_value=SimpleNamespace(session=None, user=None)
)
with pytest.raises(HTTPException) as exc_info:
await sut.confirm_password_reset(request)
await sut.refresh_session(SessionRefreshRequest(refresh_token="bad"))
assert exc_info.value.status_code == 401
assert exc_info.value.detail == "Invalid or expired verification code"
@pytest.mark.asyncio
async def test_recovery_resend_calls_reset_password_email(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
mock_reset_email = MagicMock()
mock_client.auth.reset_password_email = mock_reset_email
await sut.resend_verification(
VerificationResendRequest(
type="recovery",
email="test@example.com",
redirect_to="http://localhost:3000/reset-password",
)
)
mock_reset_email.assert_called_once_with(
"test@example.com",
options={"redirect_to": "http://localhost:3000/reset-password"},
)
@pytest.mark.asyncio
async def test_verify_verification_maps_internal_error_to_503(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
from supabase import AuthError
mock_client.auth.verify_otp = MagicMock(
side_effect=AuthError("internal_server_error", None)
)
with pytest.raises(HTTPException) as exc_info:
await sut.verify_verification(
VerificationVerifyRequest(
type="signup",
email="test@example.com",
token="123456",
)
)
assert exc_info.value.status_code == 503
assert exc_info.value.detail == "Auth service temporarily unavailable"
@pytest.mark.asyncio
async def test_create_session_maps_internal_error_to_503(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
from supabase import AuthError
mock_client.auth.sign_in_with_password = MagicMock(
side_effect=AuthError("internal_server_error", None)
)
with pytest.raises(HTTPException) as exc_info:
await sut.create_session(
SessionCreateRequest(
email="test@example.com",
password="secret123",
)
)
assert exc_info.value.status_code == 503
assert exc_info.value.detail == "Auth service temporarily unavailable"
@pytest.mark.asyncio
async def test_refresh_session_maps_bad_gateway_to_503(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
from supabase import AuthError
mock_client.auth.refresh_session = MagicMock(
side_effect=AuthError("bad_gateway", None)
)
with pytest.raises(HTTPException) as exc_info:
await sut.refresh_session(SessionRefreshRequest(refresh_token="rt"))
assert exc_info.value.status_code == 503
assert exc_info.value.detail == "Auth service temporarily unavailable"
@pytest.mark.asyncio
async def test_confirm_password_reset_maps_service_unavailable_to_503(
self, gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock]
) -> None:
sut, mock_client, _ = gateway
from supabase import AuthError
mock_client.auth.verify_otp = MagicMock(
side_effect=AuthError("service_unavailable", None)
)
with pytest.raises(HTTPException) as exc_info:
await sut.confirm_password_reset(
PasswordResetConfirmRequest(
email="test@example.com",
token="123456",
new_password="newpassword123",
)
)
assert exc_info.value.status_code == 503
assert exc_info.value.detail == "Auth service temporarily unavailable"
@pytest.mark.asyncio
async def test_get_user_by_email_uses_in_memory_cache(
async def test_get_user_by_phone_uses_in_memory_cache(
self,
gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock],
monkeypatch: pytest.MonkeyPatch,
@@ -350,9 +115,9 @@ class TestSupabaseAuthGateway:
sut, _, _ = gateway
user = SimpleNamespace(
id="user-1",
email="cached@example.com",
phone="+8613811112222",
created_at="2026-03-16T00:00:00Z",
email_confirmed_at=None,
phone_confirmed_at=None,
)
list_calls = {"count": 0}
@@ -362,9 +127,39 @@ class TestSupabaseAuthGateway:
monkeypatch.setattr("v1.auth.gateway._list_auth_users", _fake_list_auth_users)
first = await sut.get_user_by_email("cached@example.com")
second = await sut.get_user_by_email("CACHED@example.com")
first = await sut.get_user_by_phone("+8613811112222")
second = await sut.get_user_by_phone("+8613811112222")
assert first.id == "user-1"
assert second.email == "cached@example.com"
assert second.phone == "+8613811112222"
assert list_calls["count"] == 1
@pytest.mark.asyncio
async def test_search_user_ids_by_phone_supports_suffix_query(
self,
gateway: tuple[SupabaseAuthGateway, MagicMock, MagicMock],
monkeypatch: pytest.MonkeyPatch,
) -> None:
sut, _, _ = gateway
users = [
SimpleNamespace(
id="user-cn",
phone="+8613811112222",
created_at="2026-03-16T00:00:00Z",
phone_confirmed_at=None,
),
SimpleNamespace(
id="user-us",
phone="+14155552671",
created_at="2026-03-16T00:00:00Z",
phone_confirmed_at=None,
),
]
monkeypatch.setattr("v1.auth.gateway._list_auth_users", lambda _client: users)
matched_cn = await sut.search_user_ids_by_phone("13811112222")
matched_us = await sut.search_user_ids_by_phone("4155552671")
assert matched_cn == ["user-cn"]
assert matched_us == ["user-us"]
+20 -59
View File
@@ -5,72 +5,28 @@ from pydantic import ValidationError
from v1.auth.schemas import (
AuthUser,
SessionCreateRequest,
OtpSendRequest,
PhoneSessionCreateRequest,
SessionDeleteRequest,
SessionRefreshRequest,
SessionResponse,
VerificationCreateRequest,
VerificationVerifyRequest,
VerificationResendRequest,
)
def test_signup_requires_valid_email() -> None:
def test_send_otp_requires_valid_phone() -> None:
with pytest.raises(ValidationError):
VerificationCreateRequest(
username="demo", email="not-an-email", password="secret123"
)
OtpSendRequest(phone="13812345678")
def test_signup_requires_username() -> None:
def test_send_otp_accepts_e164_phone() -> None:
request = OtpSendRequest(phone="+14155552671")
assert request.phone == "+14155552671"
def test_phone_session_requires_six_digit_token() -> None:
with pytest.raises(ValidationError):
VerificationCreateRequest.model_validate(
{"email": "user@example.com", "password": "secret123"}
)
def test_signup_allows_any_invite_code_input() -> None:
request = VerificationCreateRequest(
username="demo",
email="user@example.com",
password="secret123",
invite_code="abc123",
)
assert request.invite_code == "abc123"
def test_signup_verify_requires_six_digit_token() -> None:
with pytest.raises(ValidationError):
VerificationVerifyRequest(email="user@example.com", token="abc123")
def test_signup_verify_disallows_new_password() -> None:
with pytest.raises(ValidationError):
VerificationVerifyRequest(
type="signup",
email="user@example.com",
token="123456",
new_password="secret123",
)
def test_recovery_verify_requires_new_password() -> None:
with pytest.raises(ValidationError):
VerificationVerifyRequest(
type="recovery",
email="user@example.com",
token="123456",
)
def test_signup_resend_requires_valid_email() -> None:
with pytest.raises(ValidationError):
VerificationResendRequest(email="invalid")
def test_login_requires_valid_email() -> None:
with pytest.raises(ValidationError):
SessionCreateRequest(email="invalid", password="secret123")
PhoneSessionCreateRequest(phone="+8613812345678", token="abc123")
def test_refresh_requires_token() -> None:
@@ -78,8 +34,13 @@ def test_refresh_requires_token() -> None:
SessionRefreshRequest(refresh_token="")
def test_logout_requires_token() -> None:
with pytest.raises(ValidationError):
SessionDeleteRequest(refresh_token="")
def test_session_response_maps_user() -> None:
user = AuthUser(id="user-1", email="user@example.com")
user = AuthUser(id="user-1", phone="+14155552671")
response = SessionResponse(
access_token="access",
refresh_token="refresh",
@@ -89,4 +50,4 @@ def test_session_response_maps_user() -> None:
)
assert response.user.id == "user-1"
assert response.user.email == "user@example.com"
assert response.user.phone == "+14155552671"
+33 -160
View File
@@ -2,19 +2,12 @@ from __future__ import annotations
import pytest
import v1.auth.gateway as auth_gateway_module
from v1.auth.schemas import (
AuthUser,
PasswordResetConfirmRequest,
PasswordResetRequest,
SessionCreateRequest,
OtpSendRequest,
PhoneSessionCreateRequest,
SessionRefreshRequest,
SessionResponse,
UserByEmailResponse,
VerificationCreateRequest,
VerificationCreateResponse,
VerificationResendRequest,
VerificationVerifyRequest,
)
from v1.auth.service import AuthService, AuthServiceGateway
@@ -22,23 +15,16 @@ from v1.auth.service import AuthService, AuthServiceGateway
class FakeGateway(AuthServiceGateway):
def __init__(self, response: SessionResponse) -> None:
self._response = response
self.last_create_verification_request: VerificationCreateRequest | None = None
self.last_send_otp_request: OtpSendRequest | None = None
self.last_phone_session_request: PhoneSessionCreateRequest | None = None
async def create_verification(
self, request: VerificationCreateRequest
) -> VerificationCreateResponse:
self.last_create_verification_request = request
return VerificationCreateResponse(email=request.email)
async def send_otp(self, request: OtpSendRequest) -> None:
self.last_send_otp_request = request
async def verify_verification(
self, request: VerificationVerifyRequest
async def create_phone_session(
self, request: PhoneSessionCreateRequest
) -> SessionResponse:
return self._response
async def resend_verification(self, request: VerificationResendRequest) -> None:
return None
async def create_session(self, request: SessionCreateRequest) -> SessionResponse:
self.last_phone_session_request = request
return self._response
async def refresh_session(self, request: SessionRefreshRequest) -> SessionResponse:
@@ -47,85 +33,10 @@ class FakeGateway(AuthServiceGateway):
async def delete_session(self, refresh_token: str | None) -> None:
return None
async def get_user_by_email(self, email: str) -> UserByEmailResponse:
raise NotImplementedError
async def request_password_reset(self, request: PasswordResetRequest) -> None:
raise NotImplementedError
async def confirm_password_reset(
self, request: PasswordResetConfirmRequest
) -> None:
raise NotImplementedError
class LogoutAssertingGateway(AuthServiceGateway):
def __init__(self, expected_refresh_token: str) -> None:
self._expected_refresh_token = expected_refresh_token
async def create_verification(
self, request: VerificationCreateRequest
) -> VerificationCreateResponse:
raise NotImplementedError
async def verify_verification(
self, request: VerificationVerifyRequest
) -> SessionResponse:
raise NotImplementedError
async def resend_verification(self, request: VerificationResendRequest) -> None:
raise NotImplementedError
async def create_session(self, request: SessionCreateRequest) -> SessionResponse:
raise NotImplementedError
async def refresh_session(self, request: SessionRefreshRequest) -> SessionResponse:
raise NotImplementedError
async def delete_session(self, refresh_token: str | None) -> None:
assert refresh_token == self._expected_refresh_token
async def get_user_by_email(self, email: str) -> UserByEmailResponse:
raise NotImplementedError
async def request_password_reset(self, request: PasswordResetRequest) -> None:
raise NotImplementedError
async def confirm_password_reset(
self, request: PasswordResetConfirmRequest
) -> None:
raise NotImplementedError
@pytest.mark.asyncio
async def test_logout_forwards_refresh_token() -> None:
service = AuthService(gateway=LogoutAssertingGateway("refresh-token"))
await service.delete_session("refresh-token")
@pytest.mark.asyncio
async def test_signup_resend_returns_none() -> None:
user = AuthUser(id="user-1", email="user@example.com")
token_response = SessionResponse(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
user=user,
)
service = AuthService(gateway=FakeGateway(token_response))
result = await service.resend_verification(
VerificationResendRequest(email="user@example.com")
)
assert result is None
@pytest.mark.asyncio
async def test_create_verification_ignores_invalid_invite_code() -> None:
user = AuthUser(id="user-1", email="user@example.com")
async def test_send_otp_forwards_payload() -> None:
user = AuthUser(id="user-1", phone="+8613812345678")
token_response = SessionResponse(
access_token="access",
refresh_token="refresh",
@@ -136,22 +47,15 @@ async def test_create_verification_ignores_invalid_invite_code() -> None:
gateway = FakeGateway(token_response)
service = AuthService(gateway=gateway)
await service.create_verification(
VerificationCreateRequest(
username="demo",
email="user@example.com",
password="secret123",
invite_code="bad-code",
)
)
await service.send_otp(OtpSendRequest(phone="+8613812345678"))
assert gateway.last_create_verification_request is not None
assert gateway.last_create_verification_request.invite_code is None
assert gateway.last_send_otp_request is not None
assert gateway.last_send_otp_request.phone == "+8613812345678"
@pytest.mark.asyncio
async def test_create_verification_normalizes_valid_invite_code() -> None:
user = AuthUser(id="user-1", email="user@example.com")
async def test_create_phone_session_forwards_payload() -> None:
user = AuthUser(id="user-1", phone="+8613812345678")
token_response = SessionResponse(
access_token="access",
refresh_token="refresh",
@@ -162,59 +66,28 @@ async def test_create_verification_normalizes_valid_invite_code() -> None:
gateway = FakeGateway(token_response)
service = AuthService(gateway=gateway)
await service.create_verification(
VerificationCreateRequest(
username="demo",
email="user@example.com",
password="secret123",
invite_code="a2b3",
)
response = await service.create_phone_session(
PhoneSessionCreateRequest(phone="+8613812345678", token="123456")
)
assert gateway.last_create_verification_request is not None
assert gateway.last_create_verification_request.invite_code == "A2B3"
assert gateway.last_phone_session_request is not None
assert gateway.last_phone_session_request.token == "123456"
assert response.user.phone == "+8613812345678"
@pytest.mark.asyncio
async def test_supabase_signup_passes_username_in_metadata(
monkeypatch: pytest.MonkeyPatch,
) -> None:
captured_payload: dict[str, object] = {}
class FakeSupabaseAuth:
def sign_up(self, payload: dict[str, object]) -> object:
captured_payload.update(payload)
class _User:
id = "user-1"
email = "user@example.com"
class _Session:
access_token = "access"
refresh_token = "refresh"
expires_in = 3600
token_type = "bearer"
class _Response:
user = _User()
session = None
return _Response()
class FakeClient:
auth = FakeSupabaseAuth()
monkeypatch.setattr(
auth_gateway_module.supabase_service, "get_client", lambda: FakeClient()
async def test_refresh_session_forwards_payload() -> None:
user = AuthUser(id="user-1", phone="+8613812345678")
token_response = SessionResponse(
access_token="access",
refresh_token="refresh",
expires_in=3600,
token_type="bearer",
user=user,
)
gateway = FakeGateway(token_response)
service = AuthService(gateway=gateway)
gateway = auth_gateway_module.SupabaseAuthGateway()
await gateway.create_verification(
VerificationCreateRequest(
username="demo",
email="user@example.com",
password="secret123",
)
)
response = await service.refresh_session(SessionRefreshRequest(refresh_token="rt"))
assert captured_payload["data"] == {"username": "demo"}
assert response.access_token == "access"