Start learning free

LESSON 101 OF 173 · BACKEND: USERS AND SECURITY

Only Your Own Orders

Practice

A login proves who you are. It doesn't prove that what you ask for is yours. If GET /orders/2 only checks for a login, any customer can read every order in the shop by trying 1, 2, 3…

The fix goes into the query: ask for the thing and its owner at once, with two conditions joined by AND. For example, for notes that belong to users:

const note = db.prepare(
  "SELECT id, text FROM notes WHERE id = ? AND owner_email = ?"
).get(noteId, req.user.email);

A note that belongs to someone else finds no row, just like a note that doesn't exist: .get() gives undefined. Answer both the same way: 404 Not Found. A 403 Forbidden would tell a stranger that the note exists. For orders, the owner is found through customers: orders.customer_id points to a customer, and the logged-in user is the customer with the same email.

Ana and Ben sign up and log in. Order 1 is Ana's and order 2 is Ben's:

GET /orders/1   (no token)     →  401  {"error": "Login required"}
GET /orders/1   (Ana's token)  →  200  {"id": 1, "ordered": "2026-03-02", "status": "paid"}
GET /orders/2   (Ana's token)  →  404  {"error": "Order not found"}
GET /orders/99  (Ana's token)  →  404  {"error": "Order not found"}
GET /orders/2   (Ben's token)  →  200  {"id": 2, "ordered": "2026-03-15", "status": "paid"}

Your task: add GET /orders/:orderId with loginRequired. In the route's function, turn the id from the path into a number, then select the order's id, ordered and status from orders joined with customers, only when the id matches and the customer's email is req.user.email. Answer 404 with "Order not found" when there is no row.


Assignment
Follow the Coding Tutorial to add the /orders/:orderId route that shows customers only their own orders.


Hint
The values fill the ? marks in order: orderId first, then req.user.email. Write the query as an array of pieces and join them with .join(" "), so the words don't run together.


STEP 1 OF 7
    Ctrl + Enter to check