Skip to content

Commit 0d442f5

Browse files
authored
Merge pull request #70 from OpenDash-Team/feature/51-customer-accounts
Customer accounts: register, profile, update, deactivate (#51, #53)
2 parents 015a8bb + 0e87d6d commit 0d442f5

18 files changed

Lines changed: 735 additions & 5 deletions

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,10 @@ The API provides the following endpoints:
174174
| 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.` |
175175
| 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.` |
176176
| DELETE | `/api/v1/restaurants/{restaurant_id}/menu-items/{menu_item_id}` | `Deletes a specific menu item. Returns 204 on success, 404 if not found.` |
177+
| POST | `/api/v1/customers` | `Registers a customer. Returns 201 (without the password), 409 if the email is already registered, 422 for invalid input.` |
178+
| GET | `/api/v1/customers/me` | `Returns the signed-in customer's info. Returns 401 if not signed in.` |
179+
| 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.` |
180+
| DELETE | `/api/v1/customers/me` | `Deactivates the signed-in customer's account (kept but marked inactive). Returns 204, 401 if not signed in.` |
177181

178182

179183
## API Documentation

‎backend/app/api/routes.py‎

Lines changed: 76 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
from fastapi import FastAPI, HTTPException, Depends, APIRouter
22
from json import JSONDecodeError
33

4-
from ..core.dependencies import get_restaurant_service
4+
from ..core.dependencies import get_restaurant_service, get_customer_service, get_current_customer
55
from ..schemas.restaurant import Restaurant
66
from ..schemas.restaurant_query import RestaurantQuery
77
from ..services.restaurant_service import RestaurantService
88
from ..schemas.menu_item import MenuItem
99
from ..schemas.menu_item_request import MenuItemCreate, MenuItemUpdate
1010
from ..schemas.restaurant_request import RestaurantCreate, RestaurantUpdate
11-
from ..core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError
11+
from ..core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError, DuplicateEmailError, CustomerNotFoundError, CustomerDeactivatedError
12+
from ..schemas.customer import Customer, CustomerResponse
13+
from ..schemas.error import ErrorResponse
14+
from ..schemas.customer_request import CustomerCreate, CustomerUpdate
15+
from ..services.customer_service import CustomerService
1216

1317
def create_routes(api: FastAPI | APIRouter):
1418
@api.get("/health")
@@ -121,6 +125,76 @@ def update_restaurant(restaurant_id: str, request: RestaurantUpdate):
121125
raise HTTPException(status_code=409, detail=str(e))
122126

123127

128+
@api.post(
129+
"/customers",
130+
response_model=CustomerResponse,
131+
status_code=201,
132+
summary="Register a customer",
133+
responses={409: {"model": ErrorResponse, "description": "A customer with this email already exists"}},
134+
)
135+
def register_customer(request: CustomerCreate, customer_service: CustomerService = Depends(get_customer_service)):
136+
"""Creates a new customer account. The password is stored hashed and never returned."""
137+
try:
138+
return customer_service.register_customer(request)
139+
140+
except DuplicateEmailError as e:
141+
raise HTTPException(status_code=409, detail=str(e))
142+
143+
144+
@api.get(
145+
"/customers/me",
146+
response_model=CustomerResponse,
147+
summary="Get the signed-in customer's info",
148+
responses={401: {"model": ErrorResponse, "description": "Not signed in"}},
149+
)
150+
def get_my_customer_info(current_customer: Customer = Depends(get_current_customer)):
151+
"""Returns the customer the request is signed in as. The password hash is never included."""
152+
return current_customer
153+
154+
155+
@api.patch(
156+
"/customers/me",
157+
response_model=CustomerResponse,
158+
summary="Update the signed-in customer's info and delivery address",
159+
responses={
160+
401: {"model": ErrorResponse, "description": "Not signed in"},
161+
409: {"model": ErrorResponse, "description": "Another customer already uses this email"},
162+
},
163+
)
164+
def update_my_customer_info(
165+
request: CustomerUpdate,
166+
current_customer: Customer = Depends(get_current_customer),
167+
customer_service: CustomerService = Depends(get_customer_service),
168+
):
169+
"""Changes only the fields that are sent. The password, role and id can't be changed here."""
170+
try:
171+
return customer_service.update_customer(current_customer.id, request)
172+
173+
except DuplicateEmailError as e:
174+
raise HTTPException(status_code=409, detail=str(e))
175+
176+
except (CustomerNotFoundError, CustomerDeactivatedError) as e:
177+
raise HTTPException(status_code=401, detail=str(e))
178+
179+
180+
@api.delete(
181+
"/customers/me",
182+
status_code=204,
183+
summary="Deactivate the signed-in customer's account",
184+
responses={401: {"model": ErrorResponse, "description": "Not signed in"}},
185+
)
186+
def deactivate_my_account(
187+
current_customer: Customer = Depends(get_current_customer),
188+
customer_service: CustomerService = Depends(get_customer_service),
189+
):
190+
"""The account is kept (so past orders stay valid) but marked inactive, so it can't be used again."""
191+
try:
192+
customer_service.deactivate_customer(current_customer.id)
193+
194+
except (CustomerNotFoundError, CustomerDeactivatedError) as e:
195+
raise HTTPException(status_code=401, detail=str(e))
196+
197+
124198
@api.get("/", include_in_schema=False)
125199
@api.get("/{path:path}", include_in_schema=False)
126200
def api_not_found(path: str):

‎backend/app/core/dependencies.py‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,30 @@
11
from pathlib import Path
22

3+
from fastapi import HTTPException
4+
35
from ..services.restaurant_service import RestaurantService
6+
from ..services.customer_service import CustomerService
47
from ..repositories.restaurant_repository import RestaurantRepository
8+
from ..repositories.customer_repository import CustomerRepository
9+
from ..schemas.customer import Customer
10+
511

612
def get_data_dir() -> Path:
713
data_dir = Path(__file__).resolve().parents[2] / "data"
8-
if not data_dir.exists(): data_dir.mkdir()
14+
15+
if not data_dir.exists():
16+
data_dir.mkdir()
17+
918
return data_dir
1019

1120
def get_restaurant_service():
1221
restaurant_repository = RestaurantRepository(get_data_dir() / "restaurants.json")
13-
return RestaurantService(restaurant_repository)
22+
return RestaurantService(restaurant_repository)
23+
24+
def get_customer_service() -> CustomerService:
25+
customer_repository = CustomerRepository(get_data_dir() / "customers.json")
26+
return CustomerService(customer_repository)
27+
28+
def get_current_customer() -> Customer:
29+
"""Placeholder until login (#52) is merged: rejects every request."""
30+
raise HTTPException(status_code=401, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"})

‎backend/app/core/exceptions.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,12 @@ class RestaurantNotFoundError(Exception):
33

44
class DuplicateRestaurantError(Exception):
55
"""Another restaurant already has the same name and address."""
6+
7+
class CustomerNotFoundError(Exception):
8+
"""No customer has the given ID."""
9+
10+
class DuplicateEmailError(Exception):
11+
"""Another customer is already registered with this email."""
12+
13+
class CustomerDeactivatedError(Exception):
14+
"""The customer's account has been deactivated."""

‎backend/app/core/security.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from pwdlib import PasswordHash
2+
3+
# Argon2, each hash gets its own random salt
4+
password_hash = PasswordHash.recommended()
5+
6+
7+
def hash_password(password: str) -> str:
8+
return password_hash.hash(password)
9+
10+
11+
def verify_password(password: str, hashed_password: str) -> bool:
12+
return password_hash.verify(password, hashed_password)
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from pathlib import Path
2+
3+
from .json_repository import JsonRepository
4+
from ..schemas.customer import Customer
5+
6+
7+
class CustomerRepository(JsonRepository[Customer]):
8+
def __init__(self, customers_file_path: Path) -> None:
9+
super().__init__(customers_file_path, Customer)
10+
11+
def get_all_customers(self) -> list[Customer]:
12+
return self._load_all()
13+
14+
def save_customers(self, customers: list[Customer]) -> None:
15+
self._save_all(customers)
16+
17+
def get_customer_by_id(self, customer_id: str) -> Customer | None:
18+
for customer in self.get_all_customers():
19+
if customer.id == customer_id:
20+
return customer
21+
return None
22+
23+
def get_customer_by_email(self, email: str) -> Customer | None:
24+
for customer in self.get_all_customers():
25+
if customer.email == email.lower():
26+
return customer
27+
return None

‎backend/app/schemas/customer.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import Literal
2+
3+
from pydantic import BaseModel, Field
4+
5+
from ..core.identifiers import generate_id
6+
7+
CustomerRole = Literal["customer", "owner", "admin"]
8+
9+
10+
class Customer(BaseModel):
11+
"""A customer as it is stored in customers.json (includes the password hash)."""
12+
13+
id: str = Field(default_factory=generate_id, frozen=True)
14+
name: str
15+
email: str
16+
hashedPassword: str
17+
telephone: str | None = None
18+
address: str | None = None
19+
role: CustomerRole = "customer"
20+
isActive: bool = True
21+
22+
23+
class CustomerResponse(BaseModel):
24+
"""What the API sends back about a customer. Never includes the password hash."""
25+
26+
id: str
27+
name: str
28+
email: str
29+
telephone: str | None = None
30+
address: str | None = None
31+
role: CustomerRole
32+
isActive: bool
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
from typing import Annotated
2+
3+
from pydantic import BaseModel, ConfigDict, EmailStr, Field, StringConstraints, field_validator, model_validator
4+
5+
from .restaurant_request import Address, Name, Telephone
6+
7+
# Passwords are kept exactly as typed (no space stripping), otherwise login would not match
8+
Password = Annotated[str, StringConstraints(strip_whitespace=False, min_length=8, max_length=128)]
9+
10+
11+
def normalize_email(email: str | None) -> str | None:
12+
# Emails are compared case-insensitively, so they are always stored in lowercase
13+
return email.lower() if email is not None else None
14+
15+
16+
class CustomerCreate(BaseModel):
17+
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
18+
19+
name: Name = Field(description="Customer's full name")
20+
email: EmailStr = Field(description="Email address, used to sign in. Must not already be registered")
21+
password: Password = Field(description="Password, 8-128 characters")
22+
telephone: Telephone | None = Field(None, description="Phone number: digits, spaces, '+', '(', ')', '-', '.', 7-25 characters")
23+
address: Address | None = Field(None, description="Delivery address")
24+
25+
_lowercase_email = field_validator("email")(normalize_email)
26+
27+
@field_validator("password")
28+
@classmethod
29+
def check_password_not_blank(cls, password: str) -> str:
30+
if not password.strip():
31+
raise ValueError("Password can't be only spaces")
32+
return password
33+
34+
35+
class CustomerUpdate(BaseModel):
36+
"""Only the fields that are sent get changed. A field left out or sent as null stays the same."""
37+
38+
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
39+
40+
name: Name | None = Field(None, description="New name")
41+
email: EmailStr | None = Field(None, description="New email address. Must not belong to another customer")
42+
telephone: Telephone | None = Field(None, description="New phone number")
43+
address: Address | None = Field(None, description="New delivery address")
44+
45+
_lowercase_email = field_validator("email")(normalize_email)
46+
47+
@model_validator(mode="after")
48+
def check_at_least_one_field(self):
49+
if all(value is None for value in self.model_dump().values()):
50+
raise ValueError("At least one field must be provided")
51+
return self

‎backend/app/schemas/error.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from pydantic import BaseModel
2+
3+
4+
class ErrorResponse(BaseModel):
5+
"""Body of every error the API sends on purpose (401, 404, 409...)."""
6+
7+
detail: str
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
from ..core.exceptions import CustomerDeactivatedError, CustomerNotFoundError, DuplicateEmailError
2+
from ..core.security import hash_password
3+
from ..repositories.customer_repository import CustomerRepository
4+
from ..schemas.customer import Customer
5+
from ..schemas.customer_request import CustomerCreate, CustomerUpdate
6+
7+
8+
class CustomerService:
9+
def __init__(self, repository: CustomerRepository):
10+
self.repository: CustomerRepository = repository
11+
12+
def register_customer(self, request: CustomerCreate) -> Customer:
13+
# The plain password is never stored, only its hash. Hashing is slow, so it's done
14+
# before taking the lock to keep other requests from waiting on it.
15+
data = request.model_dump(exclude={"password"})
16+
new_customer = Customer(**data, hashedPassword=hash_password(request.password))
17+
18+
with self.repository.lock():
19+
customers = self.repository.get_all_customers()
20+
self._check_email_not_taken(customers, request.email)
21+
22+
customers.append(new_customer)
23+
self.repository.save_customers(customers)
24+
25+
return new_customer
26+
27+
def get_customer_by_email(self, email: str) -> Customer | None:
28+
return self.repository.get_customer_by_email(email)
29+
30+
def get_active_customer(self, customer_id: str) -> Customer:
31+
return self._find_active(self.repository.get_all_customers(), customer_id)
32+
33+
def update_customer(self, customer_id: str, request: CustomerUpdate) -> Customer:
34+
# Fields that were not sent (or sent as null) keep their current value
35+
changes = request.model_dump(exclude_none=True)
36+
37+
with self.repository.lock():
38+
customers = self.repository.get_all_customers()
39+
customer = self._find_active(customers, customer_id)
40+
41+
if "email" in changes:
42+
other_customers = [c for c in customers if c.id != customer_id]
43+
self._check_email_not_taken(other_customers, changes["email"])
44+
45+
for field, value in changes.items():
46+
setattr(customer, field, value)
47+
48+
self.repository.save_customers(customers)
49+
50+
return customer
51+
52+
def deactivate_customer(self, customer_id: str) -> None:
53+
# Soft delete: the account stays in the file so past orders still point to a real customer,
54+
# but it can't sign in or be used anymore.
55+
with self.repository.lock():
56+
customers = self.repository.get_all_customers()
57+
customer = self._find_active(customers, customer_id)
58+
59+
customer.isActive = False
60+
self.repository.save_customers(customers)
61+
62+
def _find_active(self, customers: list[Customer], customer_id: str) -> Customer:
63+
customer = next((c for c in customers if c.id == customer_id), None)
64+
if customer is None:
65+
raise CustomerNotFoundError(f"Customer with id '{customer_id}' is not found")
66+
if not customer.isActive:
67+
raise CustomerDeactivatedError(f"Customer with id '{customer_id}' is deactivated")
68+
return customer
69+
70+
def _check_email_not_taken(self, customers: list[Customer], email: str) -> None:
71+
# Deactivated accounts still hold their email, so it can't be reused for a new account
72+
if any(customer.email == email for customer in customers):
73+
raise DuplicateEmailError(f"A customer with email '{email}' already exists")

0 commit comments

Comments
 (0)