diff --git a/app/features/auth/repository.py b/app/features/auth/repository.py index 475d564..b2857d4 100644 --- a/app/features/auth/repository.py +++ b/app/features/auth/repository.py @@ -3,7 +3,7 @@ from __future__ import annotations from datetime import datetime from uuid import UUID -from sqlalchemy import select, update +from sqlalchemy import func, or_, select, update from sqlalchemy.ext.asyncio import AsyncSession from app.db.models import ( @@ -50,6 +50,46 @@ class AuthRepository: ) return result.scalar_one_or_none() + async def find_users_by_phone_candidates( + self, + *, + exact_values: tuple[str, ...], + suffix_digits: tuple[str, ...], + limit: int = 20, + ) -> list[AppUser]: + """Return candidate users matching exact phone strings or national digit suffixes.""" + if not exact_values and not suffix_digits: + return [] + + cleaned_db_phone = func.replace( + func.replace( + func.replace( + func.replace(AppUser.phone_number, " ", ""), + "-", + "", + ), + "(", + "", + ), + ")", + "", + ) + + predicates = [] + if exact_values: + predicates.append(AppUser.phone_number.in_(exact_values)) + predicates.append(cleaned_db_phone.in_(exact_values)) + for suffix in suffix_digits: + predicates.append(cleaned_db_phone.endswith(suffix)) + + result = await self._session.execute( + select(AppUser) + .where(AppUser.phone_number.is_not(None), or_(*predicates)) + .order_by(AppUser.id.asc()) + .limit(limit) + ) + return list(result.scalars().all()) + async def create_user( self, *, diff --git a/app/features/auth/security.py b/app/features/auth/security.py index b2a0609..cf6579b 100644 --- a/app/features/auth/security.py +++ b/app/features/auth/security.py @@ -23,6 +23,37 @@ EMAIL_REGEX = re.compile( r"^[a-zA-Z0-9_%+-]+(?:\.[a-zA-Z0-9_%+-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$" ) +MIN_NATIONAL_PHONE_DIGITS = 6 + +# Prefix-free ITU-T E.164 country calling codes (1 to 3 digits). +ITU_CALLING_CODES: frozenset[str] = frozenset({ + "1", "7", + "20", "27", "30", "31", "32", "33", "34", "36", "39", "40", "41", "43", + "44", "45", "46", "47", "48", "49", "51", "52", "53", "54", "55", "56", + "57", "58", "60", "61", "62", "63", "64", "65", "66", "81", "82", "84", + "86", "90", "91", "92", "93", "94", "95", "98", + "211", "212", "213", "216", "218", + "220", "221", "222", "223", "224", "225", "226", "227", "228", "229", + "230", "231", "232", "233", "234", "235", "236", "237", "238", "239", + "240", "241", "242", "243", "244", "245", "246", "247", "248", "249", + "250", "251", "252", "253", "254", "255", "256", "257", "258", + "260", "261", "262", "263", "264", "265", "266", "267", "268", "269", + "290", "291", "297", "298", "299", + "350", "351", "352", "353", "354", "355", "356", "357", "358", "359", + "370", "371", "372", "373", "374", "375", "376", "377", "378", "379", + "380", "381", "382", "383", "385", "386", "387", "389", + "420", "421", "423", + "500", "501", "502", "503", "504", "505", "506", "507", "508", "509", + "590", "591", "592", "593", "594", "595", "596", "597", "598", "599", + "670", "672", "673", "674", "675", "676", "677", "678", "679", + "680", "681", "682", "683", "685", "686", "687", "688", "689", + "690", "691", "692", + "850", "852", "853", "855", "856", "880", "886", + "960", "961", "962", "963", "964", "965", "966", "967", "968", + "970", "971", "972", "973", "974", "975", "976", "977", + "992", "993", "994", "995", "996", "998", +}) + def base64url_encode(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") @@ -46,6 +77,86 @@ def normalize_phone_number(value: str | None) -> str: return value.strip() if value else "" +def extract_phone_digits(value: str | None) -> str: + """Return only ASCII digits from a phone string.""" + if not value: + return "" + return "".join(ch for ch in value if ch.isdigit()) + + +def _split_e164_digits(digits: str, local: str) -> bool: + """Return True when ``digits`` equals ````.""" + if len(local) < MIN_NATIONAL_PHONE_DIGITS or len(digits) <= len(local): + return False + if not digits.endswith(local): + return False + prefix = digits[: -len(local)] + return prefix in ITU_CALLING_CODES + + +def build_phone_lookup_variants( + value: str | None, +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Build exact equality values and national suffix digits for login phone lookup.""" + stripped = normalize_phone_number(value) + if not stripped: + return (), () + + digits = extract_phone_digits(stripped) + compact = re.sub(r"[\s\-()]+", "", stripped) + + exact_candidates: list[str] = [] + for candidate in (stripped, compact, f"+{digits}" if digits else ""): + if candidate and candidate not in exact_candidates: + exact_candidates.append(candidate) + + suffix_candidates: list[str] = [] + if digits and not stripped.startswith("+"): + national = digits.lstrip("0") or digits + for suffix in (digits, national): + if len(suffix) >= MIN_NATIONAL_PHONE_DIGITS and suffix not in suffix_candidates: + suffix_candidates.append(suffix) + + return tuple(exact_candidates), tuple(suffix_candidates) + + +def matches_login_phone( + stored_phone: str | None, + login_phone: str | None, +) -> bool: + """ + Determine whether ``stored_phone`` represents the same phone number as ``login_phone``. + + Supports E.164 stored values (e.g. ``+917796701290``) when a user logs in + with a local/national number without a country code (e.g. ``7796701290`` or + ``07796701290``), while rejecting partial-digit suffix collisions via prefix-free + ITU calling-code boundary checks. + """ + login_raw = normalize_phone_number(login_phone) + stored_raw = normalize_phone_number(stored_phone) + login_digits = extract_phone_digits(login_raw) + stored_digits = extract_phone_digits(stored_raw) + + if not login_digits or not stored_digits: + return False + + if login_raw.startswith("+"): + return stored_digits == login_digits + + if stored_digits == login_digits: + return True + + national = login_digits.lstrip("0") or login_digits + for candidate_local in (login_digits, national): + if _split_e164_digits(stored_digits, candidate_local): + return True + + if not stored_raw.startswith("+"): + return _split_e164_digits(login_digits, stored_digits) + + return False + + def validate_password_strength(password: str) -> None: if len(password) < 8: raise WeakPasswordError( diff --git a/app/features/auth/service.py b/app/features/auth/service.py index 540ab05..5df8345 100644 --- a/app/features/auth/service.py +++ b/app/features/auth/service.py @@ -8,6 +8,8 @@ from uuid import UUID from sqlalchemy.ext.asyncio import AsyncSession from starlette.concurrency import run_in_threadpool +from app.db.models import AppUser + from .errors import ( CurrentPasswordIncorrectError, InvalidCredentialsError, @@ -35,10 +37,13 @@ from .schema import ( UserRegisterRequest, ) from .security import ( + build_phone_lookup_variants, create_access_token, decode_access_token, + extract_phone_digits, generate_otp_code, hash_password, + matches_login_phone, normalize_email, normalize_phone_number, validate_password_strength, @@ -135,17 +140,76 @@ class AuthService: ), ) + @staticmethod + def _verify_active_user_credentials(user: AppUser, password: str) -> AppUser: + if not user.is_active: + raise UserInactiveError("Account is deactivated.") + if not verify_password(password, user.password_hash): + raise InvalidCredentialsError("Incorrect password. Please try again.") + return user + + async def _authenticate_phone_login( + self, + phone_number: str, + password: str, + ) -> AppUser: + exact_values, suffix_digits = build_phone_lookup_variants(phone_number) + if not exact_values: + raise UserNotFoundError( + "No account found with this phone number. Please sign up first." + ) + + raw_candidates = await self.repository.find_users_by_phone_candidates( + exact_values=exact_values, + suffix_digits=suffix_digits, + ) + matched = [ + candidate + for candidate in raw_candidates + if matches_login_phone(candidate.phone_number, phone_number) + ] + if not matched: + raise UserNotFoundError( + "No account found with this phone number. Please sign up first." + ) + + login_digits = extract_phone_digits(phone_number) + exact_matched = [ + candidate + for candidate in matched + if extract_phone_digits(candidate.phone_number) == login_digits + ] + candidates = exact_matched or matched + + if len(candidates) == 1: + return self._verify_active_user_credentials(candidates[0], password) + + active_candidates = [candidate for candidate in candidates if candidate.is_active] + if not active_candidates: + raise UserInactiveError("Account is deactivated.") + + verified_users = [ + candidate + for candidate in active_candidates + if verify_password(password, candidate.password_hash) + ] + if not verified_users: + raise InvalidCredentialsError("Incorrect password. Please try again.") + if len(verified_users) > 1: + raise InvalidCredentialsError( + "Multiple accounts share this phone number. Please log in with your email address." + ) + return verified_users[0] + async def login( self, request: UserLoginRequest, ) -> AuthTokenResponse: if request.phone_number: - phone = normalize_phone_number(request.phone_number) - user = await self.repository.get_user_by_phone(phone) - if user is None: - raise UserNotFoundError( - "No account found with this phone number. Please sign up first." - ) + user = await self._authenticate_phone_login( + request.phone_number, + request.password, + ) else: assert request.email is not None email = normalize_email(request.email) @@ -154,14 +218,7 @@ class AuthService: raise UserNotFoundError( "No account found with this email address. Please sign up first." ) - - if not user.is_active: - raise UserInactiveError("Account is deactivated.") - - if not verify_password(request.password, user.password_hash): - raise InvalidCredentialsError( - "Incorrect password. Please try again." - ) + user = self._verify_active_user_credentials(user, request.password) roles = await self.repository.get_user_roles(user.id) if not roles: diff --git a/tests/unit/test_phone_login.py b/tests/unit/test_phone_login.py new file mode 100644 index 0000000..f38b6cd --- /dev/null +++ b/tests/unit/test_phone_login.py @@ -0,0 +1,220 @@ +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 +