Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion repositories/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,7 @@ async def save(self, record: UserRecord) -> UserRecord:

@abstractmethod
async def get_by_email(self, email: str) -> Optional[UserRecord]:
"""Fetch user by email. Returns None if not found."""
"""Fetch user by email, case-insensitively. Returns None if not found."""

@abstractmethod
async def get_by_id(self, user_id: str) -> Optional[UserRecord]:
Expand Down
31 changes: 25 additions & 6 deletions repositories/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,30 +430,49 @@ class InMemoryUserRepository(UserRepository):
"""Dict-backed `UserRepository`. TEMPORARY - see module docstring.

Stores user accounts in memory with basic email/id lookups.

Emails are stored lowercase and looked up case-insensitively, matching
`PostgresUserRepository`. Without this, local/test runs (which default
to this stub) would let "Alice@example.com" and "alice@example.com"
register as two accounts and reject a login whose casing differs from
signup - behaviour that silently changes once DATABASE_URL is set.
"""

def __init__(self) -> None:
self._users: Dict[str, UserRecord] = {}
self._email_index: Dict[str, str] = {} # email -> user_id
self._email_index: Dict[str, str] = {} # lowercased email -> user_id
self._lock = asyncio.Lock()

async def save(self, record: UserRecord) -> UserRecord:
"""Insert or update by user_id. Idempotent, preserves created_at."""
"""Insert or update by user_id. Idempotent, preserves created_at.

Stores email in lowercase for case-insensitive lookups.
"""
async with self._lock:
existing = self._users.get(record.user_id)
created_at = existing.created_at if existing else record.created_at
email = record.email.lower()
stored = record.model_copy(
deep=True,
update={"created_at": created_at, "updated_at": datetime.now(timezone.utc)},
update={
"email": email,
"created_at": created_at,
"updated_at": datetime.now(timezone.utc),
},
)
self._users[record.user_id] = stored
self._email_index[record.email] = record.user_id
# Drop the old index entry on an email change, so the previous
# address stops resolving to this user (as it would in Postgres).
if existing is not None and existing.email != email:
if self._email_index.get(existing.email) == record.user_id:
del self._email_index[existing.email]
self._email_index[email] = record.user_id
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
return stored.model_copy(deep=True)

async def get_by_email(self, email: str) -> Optional[UserRecord]:
"""Fetch user by email. Returns None if not found."""
"""Fetch user by email. Case-insensitive. Returns None if not found."""
async with self._lock:
user_id = self._email_index.get(email)
user_id = self._email_index.get(email.lower())
stored = self._users.get(user_id) if user_id else None
return stored.model_copy(deep=True) if stored is not None else None

Expand Down
121 changes: 121 additions & 0 deletions tests/test_auth_email_case.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""
Email case-insensitivity for user accounts.

`PostgresUserRepository` stores emails lowercase and looks them up with
`LOWER(email) = LOWER($1)`, so "Alice@example.com" and "alice@example.com"
are the same account. `InMemoryUserRepository` - the default for local
development and the test suite - must behave the same way, otherwise
signup/login semantics silently change depending on whether DATABASE_URL
is set.
"""
import pytest
from fastapi.testclient import TestClient

from api.app import create_app
from core.config import AppSettings
from core.errors import ConflictError
from repositories.interfaces import UserRecord
from repositories.memory import InMemoryUserRepository
from services.auth_service import AuthService


def _user(user_id="user_1", email="Alice@Example.com"):
return UserRecord(
user_id=user_id,
email=email,
password_hash="hash",
user_type="candidate",
)


class TestInMemoryUserRepositoryEmailCase:
@pytest.mark.asyncio
async def test_save_stores_email_lowercase(self):
repo = InMemoryUserRepository()
stored = await repo.save(_user())
assert stored.email == "alice@example.com"

@pytest.mark.asyncio
@pytest.mark.parametrize(
"lookup", ["alice@example.com", "ALICE@EXAMPLE.COM", "Alice@Example.com"]
)
async def test_get_by_email_is_case_insensitive(self, lookup):
repo = InMemoryUserRepository()
await repo.save(_user())
found = await repo.get_by_email(lookup)
assert found is not None
assert found.user_id == "user_1"

@pytest.mark.asyncio
async def test_changing_email_stops_old_email_resolving(self):
repo = InMemoryUserRepository()
await repo.save(_user())
await repo.save(_user(email="Alice.New@Example.com"))
assert await repo.get_by_email("alice@example.com") is None
found = await repo.get_by_email("alice.new@example.com")
assert found is not None
assert found.user_id == "user_1"

@pytest.mark.asyncio
async def test_get_by_email_unknown_still_returns_none(self):
repo = InMemoryUserRepository()
await repo.save(_user())
assert await repo.get_by_email("bob@example.com") is None


class TestAuthServiceEmailCase:
@pytest.fixture
def service(self):
return AuthService(user_repository=InMemoryUserRepository(), settings=AppSettings())

@pytest.mark.asyncio
async def test_login_accepts_different_casing_from_signup(self, service):
signed_up, _, _ = await service.signup(
email="Alice@Example.com", password="password123", user_type="candidate"
)
logged_in, _, _ = await service.login(email="alice@example.com", password="password123")
assert logged_in.user_id == signed_up.user_id

@pytest.mark.asyncio
async def test_signup_rejects_same_email_with_different_casing(self, service):
await service.signup(
email="alice@example.com", password="password123", user_type="candidate"
)
with pytest.raises(ConflictError):
await service.signup(
email="ALICE@example.com", password="password123", user_type="recruiter"
)


class TestAuthRoutesEmailCase:
@pytest.fixture
def client(self):
with TestClient(create_app()) as c:
yield c

def test_signup_then_login_with_different_casing(self, client):
signup = client.post(
"/auth/signup",
json={"email": "Alice@Example.com", "password": "password123", "user_type": "candidate"},
)
assert signup.status_code == 200, signup.text
assert signup.json()["user"]["email"] == "alice@example.com"

login = client.post(
"/auth/login", json={"email": "alice@example.com", "password": "password123"}
)
assert login.status_code == 200, login.text
assert login.json()["user"]["user_id"] == signup.json()["user"]["user_id"]

def test_duplicate_signup_with_different_casing_conflicts(self, client):
first = client.post(
"/auth/signup",
json={"email": "alice@example.com", "password": "password123", "user_type": "candidate"},
)
assert first.status_code == 200, first.text

second = client.post(
"/auth/signup",
json={"email": "ALICE@example.com", "password": "password123", "user_type": "candidate"},
)
assert second.status_code == 409, second.text
Loading