Skip to content

Commit a99120f

Browse files
committed
enhance error handling, and update tests for owner role requirements. Adjust README for clarity on login responses
1 parent 8500968 commit a99120f

15 files changed

Lines changed: 243 additions & 167 deletions

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ Customer login returns a bearer token. Include it in the `Authorization` header
206206
| 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.` |
207207
| DELETE | `/api/v1/restaurants/{restaurant_id}/menu-items/{menu_item_id}` | `Deletes a specific menu item. Returns 204 on success, 404 if not found.` |
208208
| 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, 404 for a deactivated account, 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.` |
210210
| POST | `/api/v1/logout` | `Logs out a customer and invalidates their token` |
211211
| GET | `/api/v1/customers/me` | `Returns the signed-in customer's info. Returns 401 if not signed in.` |
212212
| 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.` |

‎backend/app/api/routes.py‎

Lines changed: 81 additions & 61 deletions
Large diffs are not rendered by default.

‎backend/app/core/dependencies.py‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@
33
import jwt
44
from fastapi import Depends, HTTPException
55
from fastapi.security import OAuth2PasswordBearer
6-
7-
from backend.app.repositories.cart_repository import CartRepository
8-
from backend.app.services.cart_service import CartService
6+
from ..repositories.cart_repository import CartRepository
7+
from ..services.cart_service import CartService
98

109
from ..core.security import SECRET_KEY, ALGORITHM
1110
from ..repositories.customer_repository import CustomerRepository
@@ -35,19 +34,17 @@ def get_customer_service() -> CustomerService:
3534

3635

3736

38-
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login", auto_error=False)
37+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login", auto_error=True)
3938

4039
def get_cart_service() -> CartService:
4140
cart_repository = CartRepository(get_data_dir() / "carts.json")
4241
return CartService(cart_repository, get_restaurant_service())
4342

4443

4544
def get_current_customer(
46-
token: str | None = Depends(oauth2_scheme),
45+
token: str = Depends(oauth2_scheme),
4746
customer_service: CustomerService = Depends(get_customer_service),
48-
) -> Customer | None:
49-
if token is None:
50-
return None
47+
) -> Customer:
5148

5249
try:
5350
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
@@ -59,9 +56,17 @@ def get_current_customer(
5956
raise HTTPException(status_code=401, detail="Not authenticated")
6057

6158
customer = customer_service.get_active_customer(customer_id)
62-
if customer is None or customer.token_version != token_version:
59+
if customer is None or customer.tokenVersion != token_version:
6360
raise HTTPException(status_code=401, detail="Not authenticated")
6461

6562
return customer
6663

6764

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+

‎backend/app/core/exceptions.py‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,9 @@ class DuplicateEmailError(Exception):
1313
class CustomerDeactivatedError(Exception):
1414
"""The customer's account has been deactivated."""
1515

16-
class NotLoggedInError(Exception):
17-
"""The customer is not logged in."""
18-
1916
class InvalidCredentialsError(Exception):
2017
"""The email or password is incorrect."""
2118

22-
class InvalidTokenError(Exception):
23-
"""The JWT token is invalid or expired."""
24-
25-
class UnauthorizedError(Exception):
26-
"""The user is not authorized to perform this action."""
27-
28-
2919
class MenuItemNotFoundError(Exception):
3020
"""No restaurant has a menu item with the given ID."""
3121

‎backend/app/schemas/customer.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ class Customer(BaseModel):
1414
name: str
1515
email: str
1616
hashedPassword: str
17-
token_version: int = 0
17+
tokenVersion: int = 0
1818
telephone: str | None = None
1919
address: str | None = None
2020
role: CustomerRole = "customer"
Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,8 @@
1-
from typing import Annotated
2-
3-
from pydantic import BaseModel, ConfigDict, EmailStr, Field, StringConstraints, field_validator, model_validator
4-
5-
from backend.app.schemas.customer_request import Password
6-
7-
from .restaurant_request import Address, Name, Telephone
8-
9-
10-
11-
1+
from pydantic import BaseModel, ConfigDict, EmailStr, Field
122

133
class LoginRequest(BaseModel):
14-
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
4+
model_config = ConfigDict(extra="forbid")
155

166
email: EmailStr = Field(description="Email address, used to sign in.")
17-
password: Password = Field(description="Password")
18-
19-
20-
21-
class LoginResponse(BaseModel):
22-
status: str = "Login Successful"
23-
7+
password: str = Field(description="Password")
248

‎backend/app/services/customer_service.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from backend.app.schemas.login_request import LoginRequest
1+
from ..schemas.login_request import LoginRequest
22

33
from ..core.exceptions import CustomerDeactivatedError, CustomerNotFoundError, DuplicateEmailError, InvalidCredentialsError
44
from ..core.security import hash_password, verify_password
@@ -69,7 +69,7 @@ def logout_customer(self, customer_id: str) -> None:
6969
customers = self.repository.get_all_customers()
7070
customer = self._find_active(customers, customer_id)
7171

72-
customer.token_version += 1
72+
customer.tokenVersion += 1
7373
self.repository.save_customers(customers)
7474

7575
def _find_active(self, customers: list[Customer], customer_id: str) -> Customer:

‎backend/requirements.txt‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,4 @@ urllib3==2.8.0
5353
uvicorn==0.53.0
5454
watchfiles==1.3.0
5555
websockets==17.1
56-
bcrypt==5.0.0
57-
passlib==1.7.4
5856
PyJWT==2.15.1

‎backend/tests/conftest.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
CURRENT_DIR = Path(__file__).resolve().parent
1313
REAL_DATA = CURRENT_DIR.parent / "data"
1414
TEST_DATA = CURRENT_DIR.parent / "tests/test-data"
15+
OWNER_ID = "cust0000000000000owner"
1516

1617
#File must be exactly this name to be known as a pytest fixture file.
1718

@@ -58,12 +59,20 @@ def sign_in_as():
5859
def make_client(customer_id):
5960
def fake_current_customer():
6061
try:
61-
return get_customer_service().get_active_customer(customer_id)
62+
customer = get_customer_service().get_active_customer(customer_id)
6263
except (CustomerNotFoundError, CustomerDeactivatedError):
6364
raise HTTPException(status_code=401, detail="Not authenticated")
65+
if customer is None:
66+
raise HTTPException(status_code=401, detail="Not authenticated")
67+
return customer
6468

6569
app = main()
6670
app.dependency_overrides[get_current_customer] = fake_current_customer
6771
return TestClient(app)
6872

6973
return make_client
74+
75+
76+
@pytest.fixture
77+
def owner_client(sign_in_as):
78+
return sign_in_as(OWNER_ID)

‎backend/tests/test_auth_endpoints.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,18 @@ def test_login_rejects_wrong_password(client):
9797
assert "access_token" not in response.json()
9898

9999

100+
def test_login_rejects_short_wrong_password(client):
101+
account, _ = register_customer(client)
102+
103+
response = client.post(
104+
"/api/v1/login",
105+
json={"email": account["email"], "password": "short"},
106+
)
107+
108+
assert response.status_code == 401
109+
assert "access_token" not in response.json()
110+
111+
100112
def test_login_rejects_unknown_email(client):
101113
response = client.post(
102114
"/api/v1/login",
@@ -118,7 +130,7 @@ def test_deactivated_customer_cannot_log_in_again(client):
118130
"/api/v1/login",
119131
json={"email": account["email"], "password": account["password"]},
120132
)
121-
assert response.status_code == 404
133+
assert response.status_code == 401
122134
assert "access_token" not in response.json()
123135

124136

@@ -182,7 +194,9 @@ def test_logout_invalidates_old_tokens_but_allows_login_again(client):
182194

183195

184196
def test_logout_requires_a_valid_token(client):
185-
assert client.post("/api/v1/logout").status_code == 401
197+
response = client.post("/api/v1/logout")
198+
assert response.status_code == 401
199+
assert response.headers["www-authenticate"] == "Bearer"
186200

187201
old_token = create_access_token({"sub": "missing-customer", "ver": 0})
188202
response = client.post(

0 commit comments

Comments
 (0)