from __future__ import annotations from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock from uuid import uuid4 import pytest from sqlalchemy.dialects import postgresql from app.features.auth.errors import ( InvalidCredentialsError, UserInactiveError, UserNotFoundError, ) from app.features.auth.repository import AuthRepository from app.features.auth.schema import UserLoginRequest from app.features.auth.security import ( build_phone_lookup_variants, hash_password, matches_login_phone, ) from app.features.auth.service import AuthService class TestPhoneMatchingHelpers: def test_e164_stored_matches_local_number_without_country_code(self) -> None: assert matches_login_phone("+917796701290", "7796701290") is True assert matches_login_phone("+917796701290", "07796701290") is True assert matches_login_phone("+91 7796701290", "7796701290") is True assert matches_login_phone("+447911123456", "07911123456") is True assert matches_login_phone("+447911123456", "7911123456") is True assert matches_login_phone("+12025550123", "2025550123") is True assert matches_login_phone("+971501234567", "501234567") is True def test_e164_stored_matches_full_number_with_or_without_plus(self) -> None: assert matches_login_phone("+917796701290", "+917796701290") is True assert matches_login_phone("+917796701290", "917796701290") is True assert matches_login_phone("+917796701290", "+91 7796701290") is True def test_rejects_partial_suffix_and_wrong_country_code(self) -> None: assert matches_login_phone("+917796701290", "796701290") is False assert matches_login_phone("+917796701290", "96701290") is False assert matches_login_phone("+12025550123", "5550123") is False assert matches_login_phone("+917796701290", "+17796701290") is False assert matches_login_phone("+917796701290", "") is False assert matches_login_phone(None, "7796701290") is False def test_legacy_local_stored_matches_local_and_with_country_prefix(self) -> None: assert matches_login_phone("7796701290", "7796701290") is True assert matches_login_phone("7796701290", "917796701290") is True def test_build_phone_lookup_variants(self) -> None: exact, suffixes = build_phone_lookup_variants("07796701290") assert "07796701290" in exact assert "+07796701290" in exact assert "07796701290" in suffixes assert "7796701290" in suffixes exact_intl, suffixes_intl = build_phone_lookup_variants("+91 7796701290") assert "+917796701290" in exact_intl assert suffixes_intl == () class TestAuthServicePhoneLogin: @staticmethod def _make_user( *, phone_number: str, password: str, country: str = "India", is_active: bool = True, email: str = "user@acupedia.test", ) -> SimpleNamespace: return SimpleNamespace( id=uuid4(), email=email, display_name="Test User", phone_number=phone_number, country=country, password_hash=hash_password(password), is_active=is_active, ) @staticmethod def _make_service(candidates: list[SimpleNamespace]) -> AuthService: session = AsyncMock() repo = AsyncMock() repo.find_users_by_phone_candidates = AsyncMock(return_value=candidates) repo.get_user_roles = AsyncMock(return_value=["practitioner"]) return AuthService( session=session, repository=repo, password_reset_email_sender=MagicMock(), ) @pytest.mark.asyncio async def test_login_succeeds_with_local_number_when_e164_is_stored(self) -> None: user = self._make_user(phone_number="+917796701290", password="ValidPass123!") service = self._make_service([user]) response = await service.login( UserLoginRequest(phone_number="7796701290", password="ValidPass123!") ) assert response.access_token assert response.user.phone_number == "+917796701290" @pytest.mark.asyncio async def test_login_rejects_partial_suffix_candidate(self) -> None: user = self._make_user(phone_number="+917796701290", password="ValidPass123!") service = self._make_service([user]) with pytest.raises(UserNotFoundError, match="No account found with this phone number"): await service.login( UserLoginRequest(phone_number="796701290", password="ValidPass123!") ) @pytest.mark.asyncio async def test_login_wrong_password_raises_invalid_credentials(self) -> None: user = self._make_user(phone_number="+917796701290", password="ValidPass123!") service = self._make_service([user]) with pytest.raises(InvalidCredentialsError, match="Incorrect password"): await service.login( UserLoginRequest(phone_number="7796701290", password="WrongPassword1!") ) @pytest.mark.asyncio async def test_login_inactive_user_raises_inactive_error(self) -> None: user = self._make_user( phone_number="+917796701290", password="ValidPass123!", is_active=False, ) service = self._make_service([user]) with pytest.raises(UserInactiveError, match="deactivated"): await service.login( UserLoginRequest(phone_number="7796701290", password="ValidPass123!") ) @pytest.mark.asyncio async def test_login_disambiguates_cross_country_local_collision_by_password(self) -> None: us_user = self._make_user( phone_number="+17796701290", password="UsPassword123!", country="United States", email="us@acupedia.test", ) in_user = self._make_user( phone_number="+917796701290", password="InPassword123!", country="India", email="in@acupedia.test", ) service = self._make_service([us_user, in_user]) response = await service.login( UserLoginRequest(phone_number="7796701290", password="InPassword123!") ) assert response.user.id == in_user.id assert response.user.email == "in@acupedia.test" @pytest.mark.asyncio async def test_login_raises_clear_error_when_collision_matches_multiple_passwords(self) -> None: us_user = self._make_user( phone_number="+17796701290", password="SharedPassword123!", country="United States", email="us@acupedia.test", ) in_user = self._make_user( phone_number="+917796701290", password="SharedPassword123!", country="India", email="in@acupedia.test", ) service = self._make_service([us_user, in_user]) with pytest.raises(InvalidCredentialsError, match="Multiple accounts share this phone number"): await service.login( UserLoginRequest(phone_number="7796701290", password="SharedPassword123!") ) class TestAuthRepositoryPhoneQuery: @pytest.mark.asyncio async def test_find_users_by_phone_candidates_executes_parameterized_query(self) -> None: captured_stmt = None expected_user = SimpleNamespace(id=uuid4(), phone_number="+917796701290") class _ScalarResult: def all(self): return [expected_user] class _ExecuteResult: def scalars(self): return _ScalarResult() async def _execute(stmt): nonlocal captured_stmt captured_stmt = stmt return _ExecuteResult() session = AsyncMock() session.execute = AsyncMock(side_effect=_execute) repo = AuthRepository(session) result = await repo.find_users_by_phone_candidates( exact_values=("7796701290", "+7796701290"), suffix_digits=("7796701290",), ) assert result == [expected_user] assert captured_stmt is not None compiled = str(captured_stmt.compile(dialect=postgresql.dialect())) assert "LIKE" in compiled assert "replace(" in compiled