diff --git a/README.md b/README.md index ecdf93a..63e52e6 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,10 @@ The API provides the following endpoints: | POST | `/api/v1/restaurants/{restaurant_id}/menu-items` | `Creates a new menu item. Returns 201, 404 if the restaurant is not found, 422 for invalid input.` | | PATCH | `/api/v1/restaurants/{restaurant_id}/menu-items/{menu_item_id}` | `Updates a menu item's fields. Returns 200, 404 if the item or restaurant is not found, 422 for invalid input.` | | DELETE | `/api/v1/restaurants/{restaurant_id}/menu-items/{menu_item_id}` | `Deletes a specific menu item. Returns 204 on success, 404 if not found.` | +| POST | `/api/v1/customers` | `Registers a customer. Returns 201 (without the password), 409 if the email is already registered, 422 for invalid input.` | +| GET | `/api/v1/customers/me` | `Returns the signed-in customer's info. Returns 401 if not signed in.` | +| PATCH | `/api/v1/customers/me` | `Updates the signed-in customer's name, email, telephone or delivery address. Returns 200, 401, 409 if the email is taken, 422 for invalid input.` | +| DELETE | `/api/v1/customers/me` | `Deactivates the signed-in customer's account (kept but marked inactive). Returns 204, 401 if not signed in.` | ## API Documentation diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py index e1d6257..315e1d0 100644 --- a/backend/app/api/routes.py +++ b/backend/app/api/routes.py @@ -1,14 +1,18 @@ from fastapi import FastAPI, HTTPException, Depends, APIRouter from json import JSONDecodeError -from ..core.dependencies import get_restaurant_service +from ..core.dependencies import get_restaurant_service, get_customer_service, get_current_customer from ..schemas.restaurant import Restaurant from ..schemas.restaurant_query import RestaurantQuery from ..services.restaurant_service import RestaurantService from ..schemas.menu_item import MenuItem from ..schemas.menu_item_request import MenuItemCreate, MenuItemUpdate from ..schemas.restaurant_request import RestaurantCreate, RestaurantUpdate -from ..core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError +from ..core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError, DuplicateEmailError, CustomerNotFoundError, CustomerDeactivatedError +from ..schemas.customer import Customer, CustomerResponse +from ..schemas.error import ErrorResponse +from ..schemas.customer_request import CustomerCreate, CustomerUpdate +from ..services.customer_service import CustomerService def create_routes(api: FastAPI | APIRouter): @api.get("/health") @@ -121,6 +125,76 @@ def update_restaurant(restaurant_id: str, request: RestaurantUpdate): raise HTTPException(status_code=409, detail=str(e)) + @api.post( + "/customers", + response_model=CustomerResponse, + status_code=201, + summary="Register a customer", + responses={409: {"model": ErrorResponse, "description": "A customer with this email already exists"}}, + ) + def register_customer(request: CustomerCreate, customer_service: CustomerService = Depends(get_customer_service)): + """Creates a new customer account. The password is stored hashed and never returned.""" + try: + return customer_service.register_customer(request) + + except DuplicateEmailError as e: + raise HTTPException(status_code=409, detail=str(e)) + + + @api.get( + "/customers/me", + response_model=CustomerResponse, + summary="Get the signed-in customer's info", + responses={401: {"model": ErrorResponse, "description": "Not signed in"}}, + ) + def get_my_customer_info(current_customer: Customer = Depends(get_current_customer)): + """Returns the customer the request is signed in as. The password hash is never included.""" + return current_customer + + + @api.patch( + "/customers/me", + response_model=CustomerResponse, + summary="Update the signed-in customer's info and delivery address", + responses={ + 401: {"model": ErrorResponse, "description": "Not signed in"}, + 409: {"model": ErrorResponse, "description": "Another customer already uses this email"}, + }, + ) + def update_my_customer_info( + request: CustomerUpdate, + current_customer: Customer = Depends(get_current_customer), + customer_service: CustomerService = Depends(get_customer_service), + ): + """Changes only the fields that are sent. The password, role and id can't be changed here.""" + try: + return customer_service.update_customer(current_customer.id, request) + + except DuplicateEmailError as e: + raise HTTPException(status_code=409, detail=str(e)) + + except (CustomerNotFoundError, CustomerDeactivatedError) as e: + raise HTTPException(status_code=401, detail=str(e)) + + + @api.delete( + "/customers/me", + status_code=204, + summary="Deactivate the signed-in customer's account", + responses={401: {"model": ErrorResponse, "description": "Not signed in"}}, + ) + def deactivate_my_account( + current_customer: Customer = Depends(get_current_customer), + customer_service: CustomerService = Depends(get_customer_service), + ): + """The account is kept (so past orders stay valid) but marked inactive, so it can't be used again.""" + try: + customer_service.deactivate_customer(current_customer.id) + + except (CustomerNotFoundError, CustomerDeactivatedError) as e: + raise HTTPException(status_code=401, detail=str(e)) + + @api.get("/", include_in_schema=False) @api.get("/{path:path}", include_in_schema=False) def api_not_found(path: str): diff --git a/backend/app/core/dependencies.py b/backend/app/core/dependencies.py index 4a8af31..9c35d45 100644 --- a/backend/app/core/dependencies.py +++ b/backend/app/core/dependencies.py @@ -1,13 +1,30 @@ from pathlib import Path +from fastapi import HTTPException + from ..services.restaurant_service import RestaurantService +from ..services.customer_service import CustomerService from ..repositories.restaurant_repository import RestaurantRepository +from ..repositories.customer_repository import CustomerRepository +from ..schemas.customer import Customer + def get_data_dir() -> Path: data_dir = Path(__file__).resolve().parents[2] / "data" - if not data_dir.exists(): data_dir.mkdir() + + if not data_dir.exists(): + data_dir.mkdir() + return data_dir def get_restaurant_service(): restaurant_repository = RestaurantRepository(get_data_dir() / "restaurants.json") - return RestaurantService(restaurant_repository) \ No newline at end of file + return RestaurantService(restaurant_repository) + +def get_customer_service() -> CustomerService: + customer_repository = CustomerRepository(get_data_dir() / "customers.json") + return CustomerService(customer_repository) + +def get_current_customer() -> Customer: + """Placeholder until login (#52) is merged: rejects every request.""" + raise HTTPException(status_code=401, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"}) diff --git a/backend/app/core/exceptions.py b/backend/app/core/exceptions.py index 3934acb..a6b04c4 100644 --- a/backend/app/core/exceptions.py +++ b/backend/app/core/exceptions.py @@ -3,3 +3,12 @@ class RestaurantNotFoundError(Exception): class DuplicateRestaurantError(Exception): """Another restaurant already has the same name and address.""" + +class CustomerNotFoundError(Exception): + """No customer has the given ID.""" + +class DuplicateEmailError(Exception): + """Another customer is already registered with this email.""" + +class CustomerDeactivatedError(Exception): + """The customer's account has been deactivated.""" diff --git a/backend/app/core/security.py b/backend/app/core/security.py new file mode 100644 index 0000000..ad8b3d3 --- /dev/null +++ b/backend/app/core/security.py @@ -0,0 +1,12 @@ +from pwdlib import PasswordHash + +# Argon2, each hash gets its own random salt +password_hash = PasswordHash.recommended() + + +def hash_password(password: str) -> str: + return password_hash.hash(password) + + +def verify_password(password: str, hashed_password: str) -> bool: + return password_hash.verify(password, hashed_password) diff --git a/backend/app/repositories/customer_repository.py b/backend/app/repositories/customer_repository.py new file mode 100644 index 0000000..624fa58 --- /dev/null +++ b/backend/app/repositories/customer_repository.py @@ -0,0 +1,27 @@ +from pathlib import Path + +from .json_repository import JsonRepository +from ..schemas.customer import Customer + + +class CustomerRepository(JsonRepository[Customer]): + def __init__(self, customers_file_path: Path) -> None: + super().__init__(customers_file_path, Customer) + + def get_all_customers(self) -> list[Customer]: + return self._load_all() + + def save_customers(self, customers: list[Customer]) -> None: + self._save_all(customers) + + def get_customer_by_id(self, customer_id: str) -> Customer | None: + for customer in self.get_all_customers(): + if customer.id == customer_id: + return customer + return None + + def get_customer_by_email(self, email: str) -> Customer | None: + for customer in self.get_all_customers(): + if customer.email == email.lower(): + return customer + return None diff --git a/backend/app/schemas/customer.py b/backend/app/schemas/customer.py new file mode 100644 index 0000000..1ffe7bd --- /dev/null +++ b/backend/app/schemas/customer.py @@ -0,0 +1,32 @@ +from typing import Literal + +from pydantic import BaseModel, Field + +from ..core.identifiers import generate_id + +CustomerRole = Literal["customer", "owner", "admin"] + + +class Customer(BaseModel): + """A customer as it is stored in customers.json (includes the password hash).""" + + id: str = Field(default_factory=generate_id, frozen=True) + name: str + email: str + hashedPassword: str + telephone: str | None = None + address: str | None = None + role: CustomerRole = "customer" + isActive: bool = True + + +class CustomerResponse(BaseModel): + """What the API sends back about a customer. Never includes the password hash.""" + + id: str + name: str + email: str + telephone: str | None = None + address: str | None = None + role: CustomerRole + isActive: bool diff --git a/backend/app/schemas/customer_request.py b/backend/app/schemas/customer_request.py new file mode 100644 index 0000000..fe5c13b --- /dev/null +++ b/backend/app/schemas/customer_request.py @@ -0,0 +1,51 @@ +from typing import Annotated + +from pydantic import BaseModel, ConfigDict, EmailStr, Field, StringConstraints, field_validator, model_validator + +from .restaurant_request import Address, Name, Telephone + +# Passwords are kept exactly as typed (no space stripping), otherwise login would not match +Password = Annotated[str, StringConstraints(strip_whitespace=False, min_length=8, max_length=128)] + + +def normalize_email(email: str | None) -> str | None: + # Emails are compared case-insensitively, so they are always stored in lowercase + return email.lower() if email is not None else None + + +class CustomerCreate(BaseModel): + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + + name: Name = Field(description="Customer's full name") + email: EmailStr = Field(description="Email address, used to sign in. Must not already be registered") + password: Password = Field(description="Password, 8-128 characters") + telephone: Telephone | None = Field(None, description="Phone number: digits, spaces, '+', '(', ')', '-', '.', 7-25 characters") + address: Address | None = Field(None, description="Delivery address") + + _lowercase_email = field_validator("email")(normalize_email) + + @field_validator("password") + @classmethod + def check_password_not_blank(cls, password: str) -> str: + if not password.strip(): + raise ValueError("Password can't be only spaces") + return password + + +class CustomerUpdate(BaseModel): + """Only the fields that are sent get changed. A field left out or sent as null stays the same.""" + + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + + name: Name | None = Field(None, description="New name") + email: EmailStr | None = Field(None, description="New email address. Must not belong to another customer") + telephone: Telephone | None = Field(None, description="New phone number") + address: Address | None = Field(None, description="New delivery address") + + _lowercase_email = field_validator("email")(normalize_email) + + @model_validator(mode="after") + def check_at_least_one_field(self): + if all(value is None for value in self.model_dump().values()): + raise ValueError("At least one field must be provided") + return self diff --git a/backend/app/schemas/error.py b/backend/app/schemas/error.py new file mode 100644 index 0000000..0bfd8e7 --- /dev/null +++ b/backend/app/schemas/error.py @@ -0,0 +1,7 @@ +from pydantic import BaseModel + + +class ErrorResponse(BaseModel): + """Body of every error the API sends on purpose (401, 404, 409...).""" + + detail: str diff --git a/backend/app/services/customer_service.py b/backend/app/services/customer_service.py new file mode 100644 index 0000000..516979f --- /dev/null +++ b/backend/app/services/customer_service.py @@ -0,0 +1,73 @@ +from ..core.exceptions import CustomerDeactivatedError, CustomerNotFoundError, DuplicateEmailError +from ..core.security import hash_password +from ..repositories.customer_repository import CustomerRepository +from ..schemas.customer import Customer +from ..schemas.customer_request import CustomerCreate, CustomerUpdate + + +class CustomerService: + def __init__(self, repository: CustomerRepository): + self.repository: CustomerRepository = repository + + def register_customer(self, request: CustomerCreate) -> Customer: + # The plain password is never stored, only its hash. Hashing is slow, so it's done + # before taking the lock to keep other requests from waiting on it. + data = request.model_dump(exclude={"password"}) + new_customer = Customer(**data, hashedPassword=hash_password(request.password)) + + with self.repository.lock(): + customers = self.repository.get_all_customers() + self._check_email_not_taken(customers, request.email) + + customers.append(new_customer) + self.repository.save_customers(customers) + + return new_customer + + def get_customer_by_email(self, email: str) -> Customer | None: + return self.repository.get_customer_by_email(email) + + def get_active_customer(self, customer_id: str) -> Customer: + return self._find_active(self.repository.get_all_customers(), customer_id) + + def update_customer(self, customer_id: str, request: CustomerUpdate) -> Customer: + # Fields that were not sent (or sent as null) keep their current value + changes = request.model_dump(exclude_none=True) + + with self.repository.lock(): + customers = self.repository.get_all_customers() + customer = self._find_active(customers, customer_id) + + if "email" in changes: + other_customers = [c for c in customers if c.id != customer_id] + self._check_email_not_taken(other_customers, changes["email"]) + + for field, value in changes.items(): + setattr(customer, field, value) + + self.repository.save_customers(customers) + + return customer + + def deactivate_customer(self, customer_id: str) -> None: + # Soft delete: the account stays in the file so past orders still point to a real customer, + # but it can't sign in or be used anymore. + with self.repository.lock(): + customers = self.repository.get_all_customers() + customer = self._find_active(customers, customer_id) + + customer.isActive = False + self.repository.save_customers(customers) + + def _find_active(self, customers: list[Customer], customer_id: str) -> Customer: + customer = next((c for c in customers if c.id == customer_id), None) + if customer is None: + raise CustomerNotFoundError(f"Customer with id '{customer_id}' is not found") + if not customer.isActive: + raise CustomerDeactivatedError(f"Customer with id '{customer_id}' is deactivated") + return customer + + def _check_email_not_taken(self, customers: list[Customer], email: str) -> None: + # Deactivated accounts still hold their email, so it can't be reused for a new account + if any(customer.email == email for customer in customers): + raise DuplicateEmailError(f"A customer with email '{email}' already exists") diff --git a/backend/requirements.txt b/backend/requirements.txt index 5f8d2ae..1ff0a45 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -2,7 +2,10 @@ agent-detector==2.0.0 annotated-doc==0.0.5 annotated-types==0.8.0 anyio==4.15.1 +argon2-cffi-bindings==26.2.0 +argon2-cffi==25.1.0 certifi==2026.7.22 +cffi==2.1.1 click==8.5.0 detect-installer==0.2.1 dnspython==2.8.0 @@ -25,6 +28,8 @@ mdurl==0.1.2 nanoid==2.0.0 packaging==26.3 pluggy==1.6.0 +pwdlib==0.4.2 +pycparser==3.12 pydantic==2.13.5 pydantic-extra-types==2.11.1 pydantic-settings==2.15.0 diff --git a/backend/sample-data/customers.json b/backend/sample-data/customers.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/backend/sample-data/customers.json @@ -0,0 +1 @@ +[] diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 6226bea..7de52c8 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -14,7 +14,7 @@ @pytest.fixture(autouse=True) def isolated_data(): - files_to_track = ["restaurants.json"] + files_to_track = ["restaurants.json", "customers.json"] for name in files_to_track: test_file = TEST_DATA / name diff --git a/backend/tests/test-data/customers.json b/backend/tests/test-data/customers.json new file mode 100644 index 0000000..606da29 --- /dev/null +++ b/backend/tests/test-data/customers.json @@ -0,0 +1,22 @@ +[ + { + "id": "cust000000000000active", + "name": "Alex Morgan", + "email": "alex@example.com", + "hashedPassword": "$argon2id$v=19$m=65536,t=3,p=4$pMImEqYcVJFExSYw9Az4gg$2UD0II/GuSsdSHMbgRxTnuG0e83GvSkr5qu6x+c1BeU", + "telephone": "+1-250-555-0111", + "address": "1234 University Way, Kelowna, BC", + "role": "customer", + "isActive": true + }, + { + "id": "cust00000000000inactive", + "name": "Sam Lee", + "email": "sam@example.com", + "hashedPassword": "$argon2id$v=19$m=65536,t=3,p=4$y10GQ6SKAnoDIUU+W419vQ$l7ZAlCATZsgNcxLwWaaPPq+C6qxsBiSgWkNw4rkDg60", + "telephone": null, + "address": null, + "role": "customer", + "isActive": false + } +] diff --git a/backend/tests/test_customer_endpoints.py b/backend/tests/test_customer_endpoints.py new file mode 100644 index 0000000..70bfc4a --- /dev/null +++ b/backend/tests/test_customer_endpoints.py @@ -0,0 +1,134 @@ +import pytest +from fastapi import HTTPException +from fastapi.testclient import TestClient + +from backend.app.core.dependencies import get_current_customer, get_customer_service +from backend.app.core.exceptions import CustomerDeactivatedError, CustomerNotFoundError +from backend.app.main import main + +ACTIVE_CUSTOMER_ID = "cust000000000000active" # Alex Morgan in test-data/customers.json + + +def new_customer(**changes): + data = {"name": "Jordan Smith", "email": "jordan@example.com", "password": "password123"} + return {**data, **changes} + + +def client_signed_in_as(customer_id): + # Login (JWT) is a separate task, so these tests pretend the request is signed in + # by replacing get_current_customer, the same way the real one will look the customer up. + def fake_current_customer(): + try: + return get_customer_service().get_active_customer(customer_id) + except (CustomerNotFoundError, CustomerDeactivatedError): + raise HTTPException(status_code=401, detail="Not authenticated") + + app = main() + app.dependency_overrides[get_current_customer] = fake_current_customer + return TestClient(app) + + +@pytest.fixture +def signed_in_client(): + return client_signed_in_as(ACTIVE_CUSTOMER_ID) + + +# POST /customers + +def test_register_returns_201_without_password(client): + response = client.post("/api/v1/customers", json=new_customer(address="1 Main St")) + + assert response.status_code == 201 + data = response.json() + assert data["id"] + assert data["email"] == "jordan@example.com" + assert data["address"] == "1 Main St" + assert data["role"] == "customer" + assert data["isActive"] is True + assert "password" not in data + assert "hashedPassword" not in data + + +def test_registered_customer_is_saved(client): + created = client.post("/api/v1/customers", json=new_customer()).json() + + # A fresh app reads customers.json again, like after a restart + response = client_signed_in_as(created["id"]).get("/api/v1/customers/me") + + assert response.status_code == 200 + assert response.json()["name"] == "Jordan Smith" + + +def test_register_with_existing_email_returns_409(client): + response = client.post("/api/v1/customers", json=new_customer(email="Alex@Example.com")) + + assert response.status_code == 409 + + +def test_register_with_invalid_email_returns_422(client): + response = client.post("/api/v1/customers", json=new_customer(email="nope")) + + assert response.status_code == 422 + + +# Not signed in + +@pytest.mark.parametrize("method", ["get", "patch", "delete"]) +def test_my_account_endpoints_need_sign_in(client, method): + kwargs = {"json": {"name": "Hacker"}} if method == "patch" else {} + + response = getattr(client, method)("/api/v1/customers/me", **kwargs) + + assert response.status_code == 401 + + +# GET /customers/me + +def test_get_my_info_returns_signed_in_customer(signed_in_client): + response = signed_in_client.get("/api/v1/customers/me") + + assert response.status_code == 200 + assert response.json()["email"] == "alex@example.com" + assert "hashedPassword" not in response.json() + + +# PATCH /customers/me + +def test_update_delivery_address(signed_in_client): + response = signed_in_client.patch("/api/v1/customers/me", json={"address": "999 New Rd, Kelowna, BC"}) + + assert response.status_code == 200 + assert response.json()["address"] == "999 New Rd, Kelowna, BC" + assert response.json()["name"] == "Alex Morgan" + + +def test_update_to_taken_email_returns_409(signed_in_client): + signed_in_client.post("/api/v1/customers", json=new_customer()) + + response = signed_in_client.patch("/api/v1/customers/me", json={"email": "jordan@example.com"}) + + assert response.status_code == 409 + + +def test_update_with_no_fields_returns_422(signed_in_client): + response = signed_in_client.patch("/api/v1/customers/me", json={}) + + assert response.status_code == 422 + + +def test_update_cannot_change_role(signed_in_client): + response = signed_in_client.patch("/api/v1/customers/me", json={"name": "Alex", "role": "admin"}) + + assert response.status_code == 422 + assert signed_in_client.get("/api/v1/customers/me").json()["role"] == "customer" + + +# DELETE /customers/me + +def test_deactivate_returns_204_and_locks_the_account(signed_in_client): + response = signed_in_client.delete("/api/v1/customers/me") + + assert response.status_code == 204 + + # The same customer can't use their account anymore + assert signed_in_client.get("/api/v1/customers/me").status_code == 401 diff --git a/backend/tests/test_customer_models.py b/backend/tests/test_customer_models.py new file mode 100644 index 0000000..297fc3b --- /dev/null +++ b/backend/tests/test_customer_models.py @@ -0,0 +1,63 @@ +import pytest +from pydantic import ValidationError + +from backend.app.schemas.customer_request import CustomerCreate, CustomerUpdate + + +def valid_customer(**changes): + data = {"name": "Jordan Smith", "email": "jordan@example.com", "password": "password123"} + return {**data, **changes} + + +def test_create_accepts_minimal_valid_customer(): + customer = CustomerCreate(**valid_customer()) + + assert customer.telephone is None + assert customer.address is None + + +def test_create_stores_email_in_lowercase(): + customer = CustomerCreate(**valid_customer(email="Jordan@Example.COM")) + + assert customer.email == "jordan@example.com" + + +def test_create_accepts_password_of_exactly_128_characters(): + customer = CustomerCreate(**valid_customer(password="a" * 128)) + + assert len(customer.password) == 128 + + +def test_create_keeps_spaces_in_password(): + customer = CustomerCreate(**valid_customer(password=" spaced out ")) + + assert customer.password == " spaced out " + + +@pytest.mark.parametrize("field, value", [ + ("email", "not-an-email"), + ("password", "short"), + ("password", " "), + ("password", "a" * 129), + ("name", ""), + ("telephone", "call me"), +]) +def test_create_rejects_invalid_values(field, value): + with pytest.raises(ValidationError): + CustomerCreate(**valid_customer(**{field: value})) + + +@pytest.mark.parametrize("field", ["role", "isActive", "id", "hashedPassword"]) +def test_create_rejects_fields_the_client_should_not_set(field): + with pytest.raises(ValidationError): + CustomerCreate(**valid_customer(**{field: "anything"})) + + +def test_update_needs_at_least_one_field(): + with pytest.raises(ValidationError): + CustomerUpdate() + + +def test_update_rejects_password_change(): + with pytest.raises(ValidationError): + CustomerUpdate(name="Alex", password="newpassword123") diff --git a/backend/tests/test_customer_repository.py b/backend/tests/test_customer_repository.py new file mode 100644 index 0000000..cd1d030 --- /dev/null +++ b/backend/tests/test_customer_repository.py @@ -0,0 +1,33 @@ +from backend.app.repositories.customer_repository import CustomerRepository +from backend.app.schemas.customer import Customer + + +def make_repository(tmp_path): + repository = CustomerRepository(tmp_path / "customers.json") + repository.save_customers([ + Customer(id="c1", name="Alex", email="alex@example.com", hashedPassword="hash"), + Customer(id="c2", name="Sam", email="sam@example.com", hashedPassword="hash"), + ]) + return repository + + +def test_get_customer_by_id(tmp_path): + repository = make_repository(tmp_path) + + assert repository.get_customer_by_id("c2").name == "Sam" + assert repository.get_customer_by_id("missing") is None + + +def test_get_customer_by_email_ignores_case(tmp_path): + repository = make_repository(tmp_path) + + assert repository.get_customer_by_email("ALEX@Example.com").id == "c1" + assert repository.get_customer_by_email("nobody@example.com") is None + + +def test_ids_stay_the_same_after_reloading(tmp_path): + repository = make_repository(tmp_path) + + reloaded = CustomerRepository(tmp_path / "customers.json") + + assert [c.id for c in reloaded.get_all_customers()] == ["c1", "c2"] diff --git a/backend/tests/test_customer_service.py b/backend/tests/test_customer_service.py new file mode 100644 index 0000000..f2eaee4 --- /dev/null +++ b/backend/tests/test_customer_service.py @@ -0,0 +1,166 @@ +import threading +from unittest.mock import MagicMock + +import pytest + +from backend.app.core.exceptions import CustomerDeactivatedError, CustomerNotFoundError, DuplicateEmailError +from backend.app.core.security import verify_password +from backend.app.repositories.customer_repository import CustomerRepository +from backend.app.schemas.customer import Customer +from backend.app.schemas.customer_request import CustomerCreate, CustomerUpdate +from backend.app.services.customer_service import CustomerService + + +def make_service(*customers): + # MagicMock (not Mock) so `with repository.lock():` works + repository = MagicMock(spec=CustomerRepository) + repository.get_all_customers.return_value = list(customers) + return CustomerService(repository), repository + + +def existing(**changes): + data = {"id": "c1", "name": "Alex", "email": "alex@example.com", "hashedPassword": "hash"} + return Customer(**{**data, **changes}) + + +# register + +def test_register_saves_customer_with_hashed_password(): + service, repository = make_service() + + customer = service.register_customer(CustomerCreate(name="Jordan", email="jordan@example.com", password="password123")) + + assert customer.hashedPassword != "password123" + assert verify_password("password123", customer.hashedPassword) + assert customer.role == "customer" + assert customer.isActive is True + repository.save_customers.assert_called_once_with([customer]) + + +def test_register_rejects_email_already_used_with_different_case(): + service, repository = make_service(existing()) + + with pytest.raises(DuplicateEmailError): + service.register_customer(CustomerCreate(name="Other", email="ALEX@example.com", password="password123")) + + repository.save_customers.assert_not_called() + + +def test_register_rejects_email_of_deactivated_account(): + service, _ = make_service(existing(isActive=False)) + + with pytest.raises(DuplicateEmailError): + service.register_customer(CustomerCreate(name="Other", email="alex@example.com", password="password123")) + + +# get + +def test_get_customer_raises_when_id_is_unknown(): + service, _ = make_service() + + with pytest.raises(CustomerNotFoundError): + service.get_active_customer("missing") + + +def test_get_active_customer_raises_for_deactivated_account(): + service, _ = make_service(existing(isActive=False)) + + with pytest.raises(CustomerDeactivatedError): + service.get_active_customer("c1") + + +# update + +def test_update_changes_only_sent_fields(): + service, repository = make_service(existing(telephone="+1-250-555-0100")) + + customer = service.update_customer("c1", CustomerUpdate(address="3333 University Way, Kelowna, BC")) + + assert customer.address == "3333 University Way, Kelowna, BC" + assert customer.telephone == "+1-250-555-0100" + assert customer.name == "Alex" + repository.save_customers.assert_called_once() + + +def test_update_rejects_email_used_by_another_customer(): + service, repository = make_service(existing(), existing(id="c2", email="taken@example.com")) + + with pytest.raises(DuplicateEmailError): + service.update_customer("c1", CustomerUpdate(email="taken@example.com")) + + repository.save_customers.assert_not_called() + + +def test_update_allows_keeping_own_email(): + service, _ = make_service(existing()) + + customer = service.update_customer("c1", CustomerUpdate(email="alex@example.com", name="Alex M")) + + assert customer.name == "Alex M" + + +def test_update_rejects_deactivated_customer(): + service, repository = make_service(existing(isActive=False)) + + with pytest.raises(CustomerDeactivatedError): + service.update_customer("c1", CustomerUpdate(name="New")) + + repository.save_customers.assert_not_called() + + +# deactivate + +def test_deactivate_marks_customer_inactive_and_keeps_them_saved(): + customer = existing() + service, repository = make_service(customer) + + service.deactivate_customer("c1") + + assert customer.isActive is False + repository.save_customers.assert_called_once_with([customer]) + + +def test_deactivate_unknown_customer_raises(): + service, _ = make_service() + + with pytest.raises(CustomerNotFoundError): + service.deactivate_customer("missing") + + +# Regression: parallel sign-ups used to overwrite each other (found in review) + +def register_in_parallel(file_path, emails): + file_path.write_text("[]") + results = [] + + def register(email): + # A new service + repository per call, like separate requests + service = CustomerService(CustomerRepository(file_path)) + try: + service.register_customer(CustomerCreate(name="Parallel", email=email, password="password123")) + results.append("ok") + except DuplicateEmailError: + results.append("duplicate") + + threads = [threading.Thread(target=register, args=(email,)) for email in emails] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + return results, CustomerRepository(file_path).get_all_customers() + + +def test_parallel_registrations_are_all_saved(tmp_path): + results, saved = register_in_parallel(tmp_path / "customers.json", [f"user{n}@example.com" for n in range(8)]) + + assert results.count("ok") == 8 + assert len(saved) == 8 + + +def test_parallel_registrations_with_same_email_create_only_one_account(tmp_path): + results, saved = register_in_parallel(tmp_path / "customers.json", ["same@example.com"] * 4) + + assert results.count("ok") == 1 + assert results.count("duplicate") == 3 + assert len(saved) == 1