Start learning free

LESSON 101 OF 173 · BACKEND: USERS AND SECURITY

Only Your Own Orders in Go

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 note Note
err := db.QueryRow("SELECT id, text FROM notes WHERE id = ? AND owner_email = ?", id, user.Email).Scan(&note.ID, &note.Text)

A note that belongs to someone else finds no row, just like a note that doesn't exist: Scan returns sql.ErrNoRows 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 GET /orders/{id} is already wrapped in loginRequired, and getOrder already reads the order's id from the path. Build a query that selects the order's id, ordered and status from orders joined with customers, only when the id matches and the customer's email is user.Email. Scan the row into an Order, answer 404 with "Order not found" when Scan returns sql.ErrNoRows, and 200 with the order otherwise.


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


Hint
The values fill the ? marks in order: id first, then user.Email. Write the query in three pieces joined with +, and end each piece but the last with a space so the words don't run together.


STEP 1 OF 9
    Ctrl + Enter to check

    Sec Owner Only in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free