Skip to content

Commit f922bed

Browse files
authored
Merge pull request #84 from OpenDash-Team/m2-authentication
M2 Authentication Systems
2 parents fde1fb7 + a99120f commit f922bed

23 files changed

Lines changed: 906 additions & 134 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: 100 additions & 21 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

2422
def create_routes(api: FastAPI | APIRouter):
2523
@api.get("/health")
@@ -45,8 +43,20 @@ def list_restaurants(params: RestaurantQuery = Depends()):
4543
raise HTTPException(status_code=400, detail=str(e))
4644
raise HTTPException(status_code=500, detail="Restaurant data failed to follow correct list[Restaurant] schema")
4745

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

5262
try:
@@ -55,8 +65,20 @@ def create_menu_item(restaurant_id: str, request: MenuItemCreate):
5565
except ValueError as e:
5666
raise HTTPException(status_code=404, detail=str(e))
5767

58-
@api.patch("/restaurants/{restaurant_id}/menu-items/{menu_item_id}", response_model=MenuItem)
59-
def update_menu_item(restaurant_id: str, menu_item_id: str, request: MenuItemUpdate):
68+
@api.patch(
69+
"/restaurants/{restaurant_id}/menu-items/{menu_item_id}",
70+
response_model=MenuItem,
71+
responses={
72+
401: {"model": ErrorResponse, "description": "Authentication required"},
73+
403: {"model": ErrorResponse, "description": "Owner role required"},
74+
},
75+
)
76+
def update_menu_item(
77+
restaurant_id: str,
78+
menu_item_id: str,
79+
request: MenuItemUpdate,
80+
_: Customer = Depends(require_owner),
81+
):
6082
restaurant_service = get_restaurant_service()
6183

6284
try:
@@ -66,8 +88,19 @@ def update_menu_item(restaurant_id: str, menu_item_id: str, request: MenuItemUpd
6688
raise HTTPException(status_code=404,detail=str(e))
6789

6890

69-
@api.delete("/restaurants/{restaurant_id}/menu-items/{menu_item_id}", status_code=204)
70-
def delete_menu_item(restaurant_id: str, menu_item_id: str):
91+
@api.delete(
92+
"/restaurants/{restaurant_id}/menu-items/{menu_item_id}",
93+
status_code=204,
94+
responses={
95+
401: {"model": ErrorResponse, "description": "Authentication required"},
96+
403: {"model": ErrorResponse, "description": "Owner role required"},
97+
},
98+
)
99+
def delete_menu_item(
100+
restaurant_id: str,
101+
menu_item_id: str,
102+
_: Customer = Depends(require_owner),
103+
):
71104
restaurant_service = get_restaurant_service()
72105

73106
try:
@@ -96,9 +129,16 @@ def get_restaurant(restaurant_id: str):
96129
response_model=Restaurant,
97130
status_code=201,
98131
summary="Create a restaurant",
99-
responses={409: {"description": "A restaurant with the same name and address already exists"}},
132+
responses={
133+
401: {"model": ErrorResponse, "description": "Authentication required"},
134+
403: {"model": ErrorResponse, "description": "Owner role required"},
135+
409: {"description": "A restaurant with the same name and address already exists"},
136+
},
100137
)
101-
def create_restaurant(request: RestaurantCreate):
138+
def create_restaurant(
139+
request: RestaurantCreate,
140+
_: Customer = Depends(require_owner),
141+
):
102142
"""Creates a new restaurant. The server generates its id, and it starts with no menu."""
103143
restaurant_service = get_restaurant_service()
104144

@@ -114,11 +154,17 @@ def create_restaurant(request: RestaurantCreate):
114154
response_model=Restaurant,
115155
summary="Update a restaurant's information",
116156
responses={
157+
401: {"model": ErrorResponse, "description": "Authentication required"},
158+
403: {"model": ErrorResponse, "description": "Owner role required"},
117159
404: {"description": "No restaurant has this id"},
118160
409: {"description": "Another restaurant already has the same name and address"},
119161
},
120162
)
121-
def update_restaurant(restaurant_id: str, request: RestaurantUpdate):
163+
def update_restaurant(
164+
restaurant_id: str,
165+
request: RestaurantUpdate,
166+
_: Customer = Depends(require_owner),
167+
):
122168
"""Changes only the fields that are sent. The id and menu can't be changed here."""
123169
restaurant_service = get_restaurant_service()
124170

@@ -151,11 +197,10 @@ def register_customer(request: CustomerCreate, customer_service: CustomerService
151197
@api.get(
152198
"/customers/me",
153199
response_model=CustomerResponse,
154-
summary="Get the signed-in customer's info",
200+
summary="Get the signed-in customer's info",
155201
responses={401: {"model": ErrorResponse, "description": "Not signed in"}},
156202
)
157203
def get_my_customer_info(current_customer: Customer = Depends(get_current_customer)):
158-
"""Returns the customer the request is signed in as. The password hash is never included."""
159204
return current_customer
160205

161206

@@ -195,12 +240,46 @@ def deactivate_my_account(
195240
customer_service: CustomerService = Depends(get_customer_service),
196241
):
197242
"""The account is kept (so past orders stay valid) but marked inactive, so it can't be used again."""
243+
244+
198245
try:
199246
customer_service.deactivate_customer(current_customer.id)
200247

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

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

205284
@api.get(
206285
"/cart",
@@ -326,4 +405,4 @@ def clear_cart(
326405
@api.get("/", include_in_schema=False)
327406
@api.get("/{path:path}", include_in_schema=False)
328407
def api_not_found(path: str):
329-
raise HTTPException(status_code=404, detail="Not Found")
408+
raise HTTPException(status_code=404, detail="Not Found")

‎backend/app/core/dependencies.py‎

Lines changed: 45 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
from pathlib import Path
22

3-
from fastapi import HTTPException
4-
5-
from ..services.restaurant_service import RestaurantService
6-
from ..services.customer_service import CustomerService
3+
import jwt
4+
from fastapi import Depends, HTTPException
5+
from fastapi.security import OAuth2PasswordBearer
6+
from ..repositories.cart_repository import CartRepository
77
from ..services.cart_service import CartService
8-
from ..repositories.restaurant_repository import RestaurantRepository
8+
9+
from ..core.security import SECRET_KEY, ALGORITHM
910
from ..repositories.customer_repository import CustomerRepository
10-
from ..repositories.cart_repository import CartRepository
11+
from ..repositories.restaurant_repository import RestaurantRepository
1112
from ..schemas.customer import Customer
13+
from ..services.customer_service import CustomerService
14+
from ..services.restaurant_service import RestaurantService
1215

1316

1417
def get_data_dir() -> Path:
@@ -23,14 +26,47 @@ def get_restaurant_service():
2326
restaurant_repository = RestaurantRepository(get_data_dir() / "restaurants.json")
2427
return RestaurantService(restaurant_repository)
2528

29+
2630
def get_customer_service() -> CustomerService:
2731
customer_repository = CustomerRepository(get_data_dir() / "customers.json")
2832
return CustomerService(customer_repository)
2933

34+
35+
36+
37+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login", auto_error=True)
38+
3039
def get_cart_service() -> CartService:
3140
cart_repository = CartRepository(get_data_dir() / "carts.json")
3241
return CartService(cart_repository, get_restaurant_service())
3342

34-
def get_current_customer() -> Customer:
35-
"""Placeholder until login (#52) is merged: rejects every request."""
36-
raise HTTPException(status_code=401, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"})
43+
44+
def get_current_customer(
45+
token: str = Depends(oauth2_scheme),
46+
customer_service: CustomerService = Depends(get_customer_service),
47+
) -> Customer:
48+
49+
try:
50+
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
51+
customer_id = payload.get("sub")
52+
token_version = payload.get("ver")
53+
if not isinstance(customer_id, str) or type(token_version) is not int:
54+
raise HTTPException(status_code=401, detail="Not authenticated")
55+
except jwt.InvalidTokenError:
56+
raise HTTPException(status_code=401, detail="Not authenticated")
57+
58+
customer = customer_service.get_active_customer(customer_id)
59+
if customer is None or customer.tokenVersion != token_version:
60+
raise HTTPException(status_code=401, detail="Not authenticated")
61+
62+
return customer
63+
64+
65+
def require_owner(
66+
current_customer: Customer = Depends(get_current_customer),
67+
) -> Customer:
68+
if current_customer.role != "owner":
69+
raise HTTPException(status_code=403, detail="Owner role required")
70+
71+
return current_customer
72+

0 commit comments

Comments
 (0)