Exercise: Study Group Sign-In

Finish the study group's sign-up, sign-in and /me routes, saving only bcrypt hashes, refusing an email that's taken with 409, answering every sign-in mistake with one 401 and handing back a JWT that lasts an hour, and let Supertest's tests check every answer against a throwaway MongoDB.

Journeyman · Node.js · REST API · Updated

By

Bright Minds Study Group is ready for accounts. You'll finish its API's three routes: sign-up, which saves a bcrypt hash of the password and refuses an email that already has an account, sign-in, which checks the password and hands back a token that lasts an hour, and /me, which answers with the student the token belongs to. Tests check every answer, with a throwaway MongoDB, so you don't need a database running to check your work.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-node-study-group-sign-in, 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-study-group-sign-in.git

Git makes a folder, exercise-node-study-group-sign-in, 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: createApp(db), the Express app and its routes, for you to finish, and sendProblem, ready to use.
  • users.js: the students in MongoDB. createUsersRepository(db) gives back addUser, findUserByEmail and findUserById, and createUserIndexes(db) makes the unique index on email. addUser gives back null when the email already has an account.
  • server.js: connects to MongoDB once, hands the database to createApp(db) and starts the API at http://localhost:3100.
  • .env.example: the two settings the server reads, MONGODB_URI and JWT_SECRET.
  • study-group.http: the requests to try with REST Client.
  • app.test.js and throwaway-database.js: the tests, and the throwaway MongoDB they use. You don't need to change either.

What to do

app.js already has createApp(db), which builds the app around the database it's given, as in Wiring MongoDB into Express: server.js hands it your MongoDB, and the tests a throwaway one. Inside it, users is the repository from users.js. app.js also has sendProblem, which sends the course's one error shape, from Error Handling and Consistent Error Responses. For now the app answers every request with a 404 that says it isn't built yet. The comment at the top of app.js lists every request it should answer:

//   POST /auth/sign-up   body { "name", "email", "password" }
//     201 { "id", "name", "email" }   A new student. Save only a bcrypt hash of the password (cost 10), with addUser.
//                                     The email is saved trimmed and lowercased: " Maya@Example.com " is saved
//                                     as "maya@example.com".
//     400 { "status": 400, "title": "Bad Request",
//           "detail": "Name, email and a password of 8 or more characters are required." }
//                                     The name, email or password is missing or empty, or the password is
//                                     shorter than 8 characters.
//     409 { "status": 409, "title": "Conflict", "detail": "That email already has an account." }
//                                     addUser gave back null: the email (trimmed and lowercased) is taken.
//
//   POST /auth/sign-in   body { "email", "password" }
//     200 { "token" }                 A JWT signed with process.env.JWT_SECRET, payload { sub: the student's id,
//                                     name: the student's name }, that expires in one hour. The email is looked up
//                                     trimmed and lowercased.
//     401 { "status": 401, "title": "Unauthorized", "detail": "Wrong email or password." }
//                                     No student has that email, or the password is wrong.
//
//   GET /me              header Authorization: Bearer <the token>
//     200 { "id", "name", "email" }   The student whose id is the token's sub.
//     401 { "status": 401, "title": "Unauthorized", "detail": "Sign in first." }
//                                     No Authorization header, or a token that was changed, signed with another
//                                     secret, or has expired.
  1. Sign-up. Check the body, hash the password with bcrypt.hash(password, 10), and save the student with users.addUser. Answer 201 with the id, name and email, or 409 when addUser gives back null.
  2. Sign-in. Look the student up by email, check the password with bcrypt.compare, and answer with a token made by jwt.sign, or the one 401 for any mistake.
  3. /me. Read the token from the Authorization header, check it with jwt.verify, and answer with the student its sub names, or 401.
  4. Send every error with sendProblem, such as sendProblem(res, 401, "Sign in first.").
  5. Remove the 404 inside createApp that says Not built yet.

No answer ever holds the password or its hash, and the secret is always process.env.JWT_SECRET, read inside the route.

Check your work

Run the tests from the exercise folder:

npm test

No server needs to be running: the tests start their own throwaway MongoDB, hand each request straight to createApp(db) built around it, and sign tokens with a test secret. At first all 16 tests fail. That's expected: each route you finish turns its tests green. A failing test's message says what it sent and what it expected, for example POST /auth/sign-up for Maya should answer 201, but it answered 404 with {"message":"Not built yet."}. If MongoDB isn't installed on your computer, the first npm test downloads a copy for the tests, once; the README says how big it is.

To try the API yourself, MongoDB must be running. Copy .env.example to a new file named .env and replace <your-secret> with a long random text of your own (the README shows a command that prints one). Then start it with npm start (or npm run dev), open study-group.http, and click Send Request above each request, from the top down. Stop it with Ctrl+C.

Hints

  • Tidy the email twice. Sign-up saves email.trim().toLowerCase(), and sign-in looks up the same, as Sign-Up and Sign-In Routes does, so MAYA@EXAMPLE.COM finds Maya.
  • Let addUser find the clash. The unique index refuses a second account, and addUser turns that into null. You don't need to look the email up before saving.
  • One answer for every sign-in mistake. An unknown email and a wrong password both get 401 and Wrong email or password., never two different messages.
  • await the slow parts. bcrypt.hash and bcrypt.compare give back promises, as Storing Passwords Safely: Hashing shows.
  • The token's facts. sub is the student's id and name their name, and { expiresIn: "1h" } sets the hour, as in Tokens: Signing In with a JWT. jwt.verify throws for a changed or expired token, so a try turns that into the 401.
  • Name the fields you send. The user from users.js holds passwordHash, so answer with an object built from its id, name and email.

When you're done

Every test is green, and with npm start running, study-group.http's requests get these answers (each request, then its answer's status line and body; your ids and token will differ):

POST /auth/sign-up  (Maya)
HTTP/1.1 201 Created
{"id":"6afc97291eb7ecc38910f4ad","name":"Maya","email":"maya@example.com"}

POST /auth/sign-up  (Maya, a second time)
HTTP/1.1 409 Conflict
{"status":409,"title":"Conflict","detail":"That email already has an account."}

POST /auth/sign-up  (Leo, password "study12")
HTTP/1.1 400 Bad Request
{"status":400,"title":"Bad Request","detail":"Name, email and a password of 8 or more characters are required."}

POST /auth/sign-in  (Maya)
HTTP/1.1 200 OK
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2YWZjOTcyOTFlYjdlY2MzODkxMGY0YWQiLCJuYW1lIjoiTWF5YSIsImlhdCI6MTc5NDkzODY2NSwiZXhwIjoxNzk0OTQyMjY1fQ.lsnxZyWtow-qsE84RwDKarqRS6Rb68yO7cfAzSD4M3A"}

POST /auth/sign-in  (the wrong password)
HTTP/1.1 401 Unauthorized
{"status":401,"title":"Unauthorized","detail":"Wrong email or password."}

GET /me  (with Maya's token)
HTTP/1.1 200 OK
{"id":"6afc97291eb7ecc38910f4ad","name":"Maya","email":"maya@example.com"}

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

Now look back at app.js. The next chapter's API has many routes that need a signed-in student, not only /me. Which lines of your /me route would every one of them repeat, and how could you write them once?

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-study-group-sign-in), 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-study-group-sign-in.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-study-group-sign-in, 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.

.env stays on your computer: .gitignore leaves it out, so git add . never sends your secret to GitHub.

So what

Every app with accounts starts with these three routes, and you've built them the way a careful team does: hashes instead of passwords, one vague 401, and a token that says who's calling without ever holding a secret.

Key terms

Related