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:

var cmd = new SqliteCommand("SELECT id, text FROM notes WHERE id = $id AND owner_email = $email", db);
cmd.Parameters.AddWithValue("$id", id);
cmd.Parameters.AddWithValue("$email", user["email"]);
using var note = cmd.ExecuteReader();

A note that belongs to someone else finds no row, just like a note that doesn't exist: note.Read() is false for both. 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: the route loggedIn.MapGet("/orders/{id}", …) is started for you, and user is the logged-in user from context.Items["user"]. Build query: select the order's id, ordered and status from orders joined with customers, only when the id matches and the customer's email is the user's. Run it with $id and $email, answer 404 with "Order not found" when there is no row, and the order as JSON otherwise.


Assignment
Follow the Coding Tutorial to finish the /orders/{id} route that shows customers only their own orders.


Hint
$id gets the path's id and $email gets user["email"]. Write the query in pieces joined with +, and end each piece with a space so the words don't run together. Between the 404 return and the last return, C# reports error CS1643 (not all code paths return a value): the last return fixes it.


STEP 1 OF 9
    Ctrl + Enter to check