Skip to content

Commit 1e6ee9c

Browse files
committed
Merge remote-tracking branch 'origin/main' into feature/Checkout-and-Initial-Order-Creation
2 parents b3dfac2 + f922bed commit 1e6ee9c

23 files changed

Lines changed: 913 additions & 143 deletions

‎.env.docker.example‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Docker/production. Generate a separate value from the local .env key.
2+
JWT_SECRET_KEY=

‎.env.example‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Local development and tests. Generate a unique value of at least 32 bytes.
2+
JWT_SECRET_KEY=

‎.github/workflows/ci.yml‎

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,30 @@ jobs:
1111
runs-on: ubuntu-latest
1212

1313
steps:
14-
- name: Checkout repository
15-
uses: actions/checkout@v4
16-
17-
- name: Set up Python 3.12
18-
uses: actions/setup-python@v5
19-
with:
20-
python-version: "3.12"
21-
22-
- name: Install dependencies from requirements.txt
23-
run: |
24-
python -m pip install --upgrade pip
25-
pip install -r backend/requirements.txt
26-
27-
- name: Set up sample testing data directory
28-
run: |
29-
mv backend/sample-data backend/data
30-
31-
- name: Run automated pytests
32-
run: |
33-
python -m pytest backend/tests -q -s --tb=short
14+
- name: Checkout repository
15+
uses: actions/checkout@v4
16+
17+
- name: Set up Python 3.12
18+
uses: actions/setup-python@v5
19+
with:
20+
python-version: "3.12"
21+
22+
- name: Install dependencies from requirements.txt
23+
run: |
24+
python -m pip install --upgrade pip
25+
pip install -r backend/requirements.txt
26+
27+
- name: Set up sample testing data directory
28+
run: |
29+
mv backend/sample-data backend/data
30+
31+
- name: Configure JWT signing key
32+
run: |
33+
cp .env.example .env
34+
SECRET=$(python -c "import secrets; print(secrets.token_urlsafe(48))")
35+
sed -i '/^JWT_SECRET_KEY=/d' .env
36+
echo "JWT_SECRET_KEY=$SECRET" >> .env
37+
38+
- name: Run automated pytests
39+
run: |
40+
python -m pytest backend/tests -q -s --tb=short

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ backend/.venv
33
backend/data
44
__pycache__
55
.env
6+
.env.*
7+
!.env.example
8+
!.env.docker.example
69

710
# Frontend
811
frontend/logs

‎README.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,16 @@ Install the required dependencies:
4949
pip install -r backend/requirements.txt
5050
```
5151

52+
### Configure the JWT Signing Key
53+
54+
Create a local environment file for development and tests:
55+
56+
```powershell
57+
Copy-Item .env.example .env
58+
```
59+
60+
Generate a secret with `python -c "import secrets; print(secrets.token_urlsafe(48))"` and put it in `.env` as `JWT_SECRET_KEY`. The key must be at least 32 bytes. Keep `.env` private; it is ignored by Git.
61+
5262
### Sample Data (Optional, First Run Only)
5363

5464
To use the sample data, rename `backend/sample-data` to `backend/data`.
@@ -142,6 +152,14 @@ Move-Item backend/sample-data data
142152

143153
### Start the Application
144154

155+
Create the Docker environment file and generate a different secret from the local `.env` key:
156+
157+
```powershell
158+
Copy-Item .env.docker.example .env.docker
159+
```
160+
161+
Set `JWT_SECRET_KEY` in `.env.docker` to its own generated value. Compose passes this file into the container; it is ignored by Git and must be provided on the production host.
162+
145163
From the repository root, run:
146164

147165
```bash
@@ -174,6 +192,8 @@ On the startup screen, choose **Customer** to browse restaurants or **Restaurant
174192

175193
The API provides the following endpoints:
176194

195+
Customer login returns a bearer token. Include it in the `Authorization` header when calling the `/customers/me` and `/cart` endpoints.
196+
177197
| Method | Path | Description |
178198
|---|---|---|
179199
| GET | `/api/v1/health` | `Checks if the API is running.` |
@@ -186,6 +206,8 @@ The API provides the following endpoints:
186206
| 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.` |
187207
| DELETE | `/api/v1/restaurants/{restaurant_id}/menu-items/{menu_item_id}` | `Deletes a specific menu item. Returns 204 on success, 404 if not found.` |
188208
| POST | `/api/v1/customers` | `Registers a customer. Returns 201 (without the password), 409 if the email is already registered, 422 for invalid input.` |
209+
| POST | `/api/v1/login` | `Authenticates a customer and returns a bearer access token. Returns 200, 401 for invalid credentials or a deactivated account, 422 for invalid input.` |
210+
| POST | `/api/v1/logout` | `Logs out a customer and invalidates their token` |
189211
| GET | `/api/v1/customers/me` | `Returns the signed-in customer's info. Returns 401 if not signed in.` |
190212
| 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.` |
191213
| DELETE | `/api/v1/customers/me` | `Deactivates the signed-in customer's account (kept but marked inactive). Returns 204, 401 if not signed in.` |

‎backend/app/api/routes.py‎

Lines changed: 108 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,23 @@
11
from fastapi import FastAPI, HTTPException, Depends, APIRouter, Path
22
from json import JSONDecodeError
3-
4-
from ..core.dependencies import get_restaurant_service, get_customer_service, get_current_customer, get_cart_service
3+
from ..core.dependencies import get_restaurant_service, get_customer_service, get_current_customer, get_cart_service, require_owner
54
from ..schemas.restaurant import Restaurant
65
from ..schemas.restaurant_query import RestaurantQuery
76
from ..services.restaurant_service import RestaurantService
87
from ..schemas.menu_item import MenuItem
98
from ..schemas.menu_item_request import MenuItemCreate, MenuItemUpdate
109
from ..schemas.restaurant_request import RestaurantCreate, RestaurantUpdate
11-
from ..core.exceptions import (
12-
DuplicateRestaurantError, RestaurantNotFoundError,
13-
DuplicateEmailError, CustomerNotFoundError, CustomerDeactivatedError,
14-
MenuItemNotFoundError, MenuItemUnavailableError, DifferentRestaurantError, CartItemNotFoundError, CartQuantityError,
15-
)
10+
from ..core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError, DuplicateEmailError, CustomerNotFoundError, CustomerDeactivatedError, InvalidCredentialsError, MenuItemNotFoundError, MenuItemUnavailableError, DifferentRestaurantError, CartQuantityError, CartItemNotFoundError
1611
from ..schemas.customer import Customer, CustomerResponse
1712
from ..schemas.error import ErrorResponse
18-
from ..schemas.customer_request import CustomerCreate, CustomerUpdate
19-
from ..services.customer_service import CustomerService
2013
from ..schemas.cart import CartResponse
2114
from ..schemas.cart_request import CartItemAdd, CartItemUpdate
2215
from ..services.cart_service import CartService
16+
from ..schemas.customer_request import CustomerCreate, CustomerUpdate
17+
from ..services.customer_service import CustomerService
18+
from ..schemas.login_request import LoginRequest
19+
from ..schemas.token import Token
20+
from ..core import security
2321
from ..core.dependencies import get_checkout_service
2422
from ..services.checkout_service import CheckoutService
2523
from ..schemas.order import Order
@@ -49,8 +47,20 @@ def list_restaurants(params: RestaurantQuery = Depends()):
4947
raise HTTPException(status_code=400, detail=str(e))
5048
raise HTTPException(status_code=500, detail="Restaurant data failed to follow correct list[Restaurant] schema")
5149

52-
@api.post("/restaurants/{restaurant_id}/menu-items", response_model=MenuItem, status_code=201)
53-
def create_menu_item(restaurant_id: str, request: MenuItemCreate):
50+
@api.post(
51+
"/restaurants/{restaurant_id}/menu-items",
52+
response_model=MenuItem,
53+
status_code=201,
54+
responses={
55+
401: {"model": ErrorResponse, "description": "Authentication required"},
56+
403: {"model": ErrorResponse, "description": "Owner role required"},
57+
},
58+
)
59+
def create_menu_item(
60+
restaurant_id: str,
61+
request: MenuItemCreate,
62+
_: Customer = Depends(require_owner),
63+
):
5464
restaurant_service = get_restaurant_service()
5565

5666
try:
@@ -59,8 +69,20 @@ def create_menu_item(restaurant_id: str, request: MenuItemCreate):
5969
except ValueError as e:
6070
raise HTTPException(status_code=404, detail=str(e))
6171

62-
@api.patch("/restaurants/{restaurant_id}/menu-items/{menu_item_id}", response_model=MenuItem)
63-
def update_menu_item(restaurant_id: str, menu_item_id: str, request: MenuItemUpdate):
72+
@api.patch(
73+
"/restaurants/{restaurant_id}/menu-items/{menu_item_id}",
74+
response_model=MenuItem,
75+
responses={
76+
401: {"model": ErrorResponse, "description": "Authentication required"},
77+
403: {"model": ErrorResponse, "description": "Owner role required"},
78+
},
79+
)
80+
def update_menu_item(
81+
restaurant_id: str,
82+
menu_item_id: str,
83+
request: MenuItemUpdate,
84+
_: Customer = Depends(require_owner),
85+
):
6486
restaurant_service = get_restaurant_service()
6587

6688
try:
@@ -70,8 +92,19 @@ def update_menu_item(restaurant_id: str, menu_item_id: str, request: MenuItemUpd
7092
raise HTTPException(status_code=404,detail=str(e))
7193

7294

73-
@api.delete("/restaurants/{restaurant_id}/menu-items/{menu_item_id}", status_code=204)
74-
def delete_menu_item(restaurant_id: str, menu_item_id: str):
95+
@api.delete(
96+
"/restaurants/{restaurant_id}/menu-items/{menu_item_id}",
97+
status_code=204,
98+
responses={
99+
401: {"model": ErrorResponse, "description": "Authentication required"},
100+
403: {"model": ErrorResponse, "description": "Owner role required"},
101+
},
102+
)
103+
def delete_menu_item(
104+
restaurant_id: str,
105+
menu_item_id: str,
106+
_: Customer = Depends(require_owner),
107+
):
75108
restaurant_service = get_restaurant_service()
76109

77110
try:
@@ -100,9 +133,16 @@ def get_restaurant(restaurant_id: str):
100133
response_model=Restaurant,
101134
status_code=201,
102135
summary="Create a restaurant",
103-
responses={409: {"description": "A restaurant with the same name and address already exists"}},
136+
responses={
137+
401: {"model": ErrorResponse, "description": "Authentication required"},
138+
403: {"model": ErrorResponse, "description": "Owner role required"},
139+
409: {"description": "A restaurant with the same name and address already exists"},
140+
},
104141
)
105-
def create_restaurant(request: RestaurantCreate):
142+
def create_restaurant(
143+
request: RestaurantCreate,
144+
_: Customer = Depends(require_owner),
145+
):
106146
"""Creates a new restaurant. The server generates its id, and it starts with no menu."""
107147
restaurant_service = get_restaurant_service()
108148

@@ -118,11 +158,17 @@ def create_restaurant(request: RestaurantCreate):
118158
response_model=Restaurant,
119159
summary="Update a restaurant's information",
120160
responses={
161+
401: {"model": ErrorResponse, "description": "Authentication required"},
162+
403: {"model": ErrorResponse, "description": "Owner role required"},
121163
404: {"description": "No restaurant has this id"},
122164
409: {"description": "Another restaurant already has the same name and address"},
123165
},
124166
)
125-
def update_restaurant(restaurant_id: str, request: RestaurantUpdate):
167+
def update_restaurant(
168+
restaurant_id: str,
169+
request: RestaurantUpdate,
170+
_: Customer = Depends(require_owner),
171+
):
126172
"""Changes only the fields that are sent. The id and menu can't be changed here."""
127173
restaurant_service = get_restaurant_service()
128174

@@ -155,11 +201,10 @@ def register_customer(request: CustomerCreate, customer_service: CustomerService
155201
@api.get(
156202
"/customers/me",
157203
response_model=CustomerResponse,
158-
summary="Get the signed-in customer's info",
204+
summary="Get the signed-in customer's info",
159205
responses={401: {"model": ErrorResponse, "description": "Not signed in"}},
160206
)
161207
def get_my_customer_info(current_customer: Customer = Depends(get_current_customer)):
162-
"""Returns the customer the request is signed in as. The password hash is never included."""
163208
return current_customer
164209

165210

@@ -199,12 +244,46 @@ def deactivate_my_account(
199244
customer_service: CustomerService = Depends(get_customer_service),
200245
):
201246
"""The account is kept (so past orders stay valid) but marked inactive, so it can't be used again."""
247+
248+
202249
try:
203250
customer_service.deactivate_customer(current_customer.id)
204251

205252
except (CustomerNotFoundError, CustomerDeactivatedError) as e:
206253
raise HTTPException(status_code=401, detail=str(e))
254+
255+
@api.post(
256+
"/login",
257+
response_model=Token,
258+
status_code=200,
259+
summary="Login a customer",
260+
responses={401: {"description": "Invalid credentials or deactivated account"}},
261+
)
262+
def login_customer(request: LoginRequest, customer_service: CustomerService = Depends(get_customer_service)):
263+
"""Authenticates a customer and returns a login response."""
264+
try:
265+
customer = customer_service.login_customer(request)
266+
token = security.create_access_token(data={"sub": str(customer.id), "ver": customer.tokenVersion})
267+
return Token(access_token=token, token_type="bearer")
207268

269+
except CustomerDeactivatedError as e:
270+
raise HTTPException(status_code=401, detail=str(e))
271+
except (InvalidCredentialsError) as e:
272+
raise HTTPException(status_code=401, detail=str(e))
273+
274+
@api.post(
275+
"/logout",
276+
status_code=200,
277+
summary="Logout a customer",
278+
responses={401: {"description": "Not authenticated or token already invalidated"}},
279+
)
280+
def logout_customer(
281+
current_customer: Customer = Depends(get_current_customer),
282+
customer_service: CustomerService = Depends(get_customer_service),
283+
) -> dict[str, str]:
284+
"""Invalidates the customer's current token(s) and logs them out."""
285+
customer_service.logout_customer(current_customer.id)
286+
return {"message": "Successfully logged out."}
208287

209288
@api.get(
210289
"/cart",
@@ -326,22 +405,15 @@ def clear_cart(
326405
except CustomerDeactivatedError as e:
327406
raise HTTPException(status_code=401, detail=str(e))
328407

329-
330-
@api.get("/", include_in_schema=False)
331-
@api.get("/{path:path}", include_in_schema=False)
332-
def api_not_found(path: str):
333-
raise HTTPException(status_code=404, detail="Not Found")
334-
335-
336408
@api.post(
337409
"/checkout",
338410
response_model=Order,
339411
status_code=201,
340412
summary="Checkout the current customer's active cart",
341413
responses={
342-
401: {"description": "Not authenticated"},
343-
403: {"description": "Customer cannot check out"},
344-
409: {"description": "Cart or menu validation failed"},
414+
401: { "model": ErrorResponse, "description": "Not authenticated",},
415+
403: {"model": ErrorResponse, "description": "Customer cannot check out",},
416+
409: {"model": ErrorResponse, "description": "Cart or menu validation failed",},
345417
},
346418
)
347419
def checkout(
@@ -364,3 +436,9 @@ def checkout(
364436

365437
except CheckoutValidationError as e:
366438
raise HTTPException(status_code=409, detail=str(e),) from e
439+
440+
441+
@api.get("/", include_in_schema=False)
442+
@api.get("/{path:path}", include_in_schema=False)
443+
def api_not_found(path: str):
444+
raise HTTPException(status_code=404, detail="Not Found")

0 commit comments

Comments
 (0)