Exercise: Team Task Board

Finish Crew Board's task API with a requireUser and a requireRole middleware and an ownership check, so anyone signed in reads the board, members change only their own tasks and only an admin deletes, and let Supertest's tests check every rule as each kind of user.

Journeyman · Node.js · REST API · Updated

By

Crew Board's team has a task board API with working sign-in, and nothing else checks who's asking. You'll add the rules the team agreed on: anyone signed in reads the board and adds tasks, members change only their own tasks, and only an admin deletes. The sign-in route is ready, so the work is all authorization: two middleware functions, an ownership check and the four task routes that use them. Tests sign in as each kind of user and check every rule as you go.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-node-team-task-board, also linked from the Exercise box beside the lesson. Clone it into your nodejs-course folder. In VS Code's terminal:

cd ~/nodejs-course
git clone https://github.com/ask-codey/exercise-node-team-task-board.git

Git makes a folder, exercise-node-team-task-board, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and install the packages:

npm install

Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder.

The folder holds:

  • app.js: the Express app, export const app = express(), for you to finish. The sign-in route is already mounted.
  • send-problem.js: the ready sendProblem(res, status, detail), which sends every error in the course's one shape.
  • sign-in.js: the ready sign-in route, POST /auth/sign-in. Its token's payload holds the user's id as sub, their name and their role.
  • users.js: the team: Maya (admin, id 1), Theo (member, id 2) and Sofia (member, id 3), with hashed passwords. The practice passwords are practice-maya, practice-theo and practice-sofia.
  • tasks.js: the four tasks and the ready functions that read and change them: allTasks, findTask, addTask, updateTask and removeTask. Its top comment says what each one does.
  • server.js: starts the API at http://localhost:3100. .env.example holds a practice secret for it.
  • crew-board.http: the requests to try with REST Client, signing in first.
  • app.test.js: the tests, which sign in as Maya, Theo and Sofia and send requests with Supertest. You don't need to change it.

What to do

app.js answers every task request with a 404 that says it isn't built yet. Every error answer has the course's one error shape from Error Handling and Consistent Error Responses, { status, title, detail }, sent with the ready sendProblem in send-problem.js: sendProblem(res, 404, "There's no task 99.") answers {"status":404,"title":"Not Found","detail":"There's no task 99."}. The comment at the top of app.js lists every request it should answer, with each error as its status and its detail:

//   Any task route, when the request has no Authorization header, or one that doesn't start "Bearer "
//                          401, "Sign in first."
//   Any task route, when the token isn't valid or has expired
//                          401, "That token isn't valid or has expired. Sign in again."
//
//   GET    /tasks          200, every task
//   POST   /tasks          201, the new task { id, title, ownerId, done: false }, owned by the signed-in user
//                          ({ "title": "Plan the team lunch" } as Theo makes task 5 with ownerId 2; an ownerId
//                          in the body is ignored)
//   PATCH  /tasks/2        200, the changed task, when the signed-in user owns task 2 or is an admin
//                          403, "Only the task's owner or an admin may change it." for anyone else
//   PATCH  /tasks/99       404, "There's no task 99."
//   DELETE /tasks/2        204, no body, when the signed-in user is an admin
//                          403, "You need the admin role for that." for anyone else
//   DELETE /tasks/99       404, "There's no task 99." (for an admin)
  1. Write requireUser. Read the Authorization header, verify its token with jwt.verify and process.env.JWT_SECRET, set req.user to { id, name, role } (the id is the payload's sub), and call next(). Answer the two 401s when there's no token, or when it isn't valid or has expired.
  2. Write requireRole(role). It gives back a middleware that answers the 403 above, with the role's name in the detail, when req.user.role isn't that role, and calls next() when it is.
  3. Write the four task routes, each with requireUser, in place of the placeholder at the bottom of app.js. Read the board with allTasks(), and make each new task with addTask(title, req.user.id).
  4. Check ownership in PATCH /tasks/:id. Find the task first (404 when there's none), then let the owner or an admin change it with updateTask(task, req.body), and answer 403 for anyone else.
  5. Let only an admin delete. Put requireRole("admin") after requireUser on DELETE /tasks/:id, then answer 404 for a task that doesn't exist, or remove it and answer 204.

Check your work

Run the tests from the exercise folder:

npm test

No server needs to be running, and you don't need a .env file for the tests: they set a practice secret of their own. At first all 15 tests fail. That's expected: each rule you add turns its tests green. A failing test's message says what it sent and what it expected, for example PATCH /tasks/3 as Theo should answer 403, but it answered 200.

To try the API yourself, copy .env.example to a new file named .env (Git leaves .env out, as Settings from Environment Variables explains), then start it with npm start (or npm run dev, which restarts it each time you save). Open crew-board.http and click Send Request above each request, from the top: the two sign-in requests save Theo's and Maya's tokens, and the requests below them send those tokens. Stop the server with Ctrl+C.

Hints

  • Start with requireUser. Every task test needs it, so nothing else can pass until it works. Requiring a Signed-In User builds one step by step.
  • requireUser before requireRole. requireRole reads req.user, which only requireUser sets, so a request with no token must get 401 before any role is checked.
  • A function that makes a middleware. requireRole("admin") runs once and gives back (req, res, next) => { ... }, as Roles and Ownership: 401 or 403 shows.
  • Route ids are text. req.params.id is the text "2", and findTask wants the number 2, so turn it into a number first, as Route and Query Parameters does.
  • The owner comes from the token. Compare the task's ownerId with req.user.id, and give new tasks req.user.id as their owner, never an id from req.body.
  • No body on a 204. res.status(204).end() answers with no body.

When you're done

Every test is green, and with npm start running, crew-board.http's requests get these answers (each request, then its answer's status line and body):

GET /tasks (no token)
HTTP/1.1 401 Unauthorized
{"status":401,"title":"Unauthorized","detail":"Sign in first."}

POST /tasks (Theo, with "ownerId": 3 in the body)
HTTP/1.1 201 Created
{"id":5,"title":"Plan the team lunch","ownerId":2,"done":false}

PATCH /tasks/3 (Theo)
HTTP/1.1 403 Forbidden
{"status":403,"title":"Forbidden","detail":"Only the task's owner or an admin may change it."}

PATCH /tasks/3 (Maya)
HTTP/1.1 200 OK
{"id":3,"title":"Fix both typos on the sign-in page","ownerId":3,"done":true}

DELETE /tasks/4 (Theo)
HTTP/1.1 403 Forbidden
{"status":403,"title":"Forbidden","detail":"You need the admin role for that."}

DELETE /tasks/4 (Maya)
HTTP/1.1 204 No Content

Now look back at app.js. If the team adds a third role, lead, who may delete tasks too, what would change in requireRole, and what would change in the routes that use it?

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.

  1. On GitHub, click +, then New repository. Name it (for example exercise-node-team-task-board), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-node-team-task-board.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-node-team-task-board, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

Every API with accounts runs these same checks: who are you, what kind of user are you, and is this yours? Written once as middleware and tested as each kind of user, they keep a team's tasks safe from the request nobody meant to allow.

Key terms

Related