Start learning free

LESSON 23 OF 58 · FULL-STACK: LOGIN WITH COOKIES

Admins Only

Practice

Logging in answers "who are you?". Some actions also need "what may you do?". Each user row now has a role: "customer" or "admin", and requireLogin loads it into req.user (given). Sam is the shop's admin; Ana and Ben are customers.

The storefront shows the "New product" form only to admins (given). That keeps the page tidy, not safe: anyone logged in can send POST /api/products with their cookie from a terminal or the browser's console. The server decides; the page only hides.

A route can list several functions. Express runs them one after the other, and each one either answers or calls next() to hand the request on. For example:

function logRequest(req, res, next) {
  console.log(req.method, req.path);
  next();
}

app.get("/api/orders", logRequest, requireLogin, listOrders);

401 means "log in first". 403 Forbidden means "you are logged in, and still not allowed". Your server must answer:

POST /api/login     {"email": "ana@example.com", …}                  →  200  {"email": "ana@example.com", "role": "customer"}
POST /api/products  {"name": "Free mug", "price": 0, "stock": 99}   →  403  {"error": "Admins only"}
POST /api/products  {"name": "Doormat", "price": 18, "stock": 10}  →  201  (Sam's form; the page adds "Doormat $18")

Your task: in server/app.js, write adminRequired (403 {"error": "Admins only"} unless the user's role is "admin"), a handler addProduct that inserts the product and answers 201 with the new row, and the route POST /api/products that runs requireLogin, adminRequired and addProduct, in that order.


Assignment
Follow the Coding Tutorial to write the adminRequired middleware, the addProduct handler and the route that chains them.


Hint
adminRequired runs after requireLogin, so req.user is already there. To answer with the new row, look it up by result.lastInsertRowid.


STEP 1 OF 9
    Ctrl + Enter to check