Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
76 changes: 74 additions & 2 deletions backend/app/api/routes.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
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.customer_request import CustomerCreate, CustomerUpdate
from ..services.customer_service import CustomerService

def create_routes(api: FastAPI | APIRouter):
@api.get("/health")
Expand Down Expand Up @@ -121,6 +124,75 @@ 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: {"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: {"description": "Not signed in"}},
)
def get_my_customer_info(current_customer: Customer = Depends(get_current_customer)):
return current_customer


@api.patch(
"/customers/me",
response_model=CustomerResponse,
summary="Update the signed-in customer's info and delivery address",
responses={
401: {"description": "Not signed in"},
409: {"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: {"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):
Expand Down
30 changes: 28 additions & 2 deletions backend/app/core/dependencies.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,39 @@
from pathlib import Path

from fastapi import HTTPException, status

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)
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:
"""Returns the signed-in customer for protected endpoints.

Placeholder until the JWT login (#52) is merged: it rejects every request, so the
protected endpoints are locked by default. The auth work replaces the body with
token decoding + customer_service.get_active_customer(customer_id).
"""
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
9 changes: 9 additions & 0 deletions backend/app/core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
13 changes: 13 additions & 0 deletions backend/app/core/security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from pwdlib import PasswordHash

# Argon2 hashing. Each hash gets its own random salt, so no secret key is needed here.
# (The SECRET_KEY in .env is only for signing login tokens.)
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)
27 changes: 27 additions & 0 deletions backend/app/repositories/customer_repository.py
Original file line number Diff line number Diff line change
@@ -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
32 changes: 32 additions & 0 deletions backend/app/schemas/customer.py
Original file line number Diff line number Diff line change
@@ -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
51 changes: 51 additions & 0 deletions backend/app/schemas/customer_request.py
Original file line number Diff line number Diff line change
@@ -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
84 changes: 84 additions & 0 deletions backend/app/services/customer_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
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(self, customer_id: str) -> Customer:
customer = self.repository.get_customer_by_id(customer_id)
if customer is None:
raise CustomerNotFoundError(f"Customer with id '{customer_id}' is not found")
return 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:
"""Like get_customer, but a deactivated account counts as an error.
Used for anything a customer does while signed in (profile, cart, checkout)."""
customer = self.get_customer(customer_id)
if not customer.isActive:
raise CustomerDeactivatedError(f"Customer with id '{customer_id}' is deactivated")
return customer

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.lower() for customer in customers):
raise DuplicateEmailError(f"A customer with email '{email}' already exists")
5 changes: 5 additions & 0 deletions backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions backend/sample-data/customers.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
Loading
Loading