Sign-Up and Sign-In Routes

A sign-up route hashes the password, saves the student behind a unique index on email and answers 409 for an email that's taken, and a sign-in route checks the password with compare and answers one vague 401 for any mistake, never sending a hash back.

Journeyman · Node.js · REST API · MongoDB · Updated

By

After this lesson you can

  • Write a sign-up route that hashes the password, answers 201, and refuses a used email with 409 using a unique index
  • Write a sign-in route that checks the password with compare and answers 401 with one vague message for any mistake
  • Keep the password and its hash out of every response and every log

Key takeaways

  • A unique index on email makes MongoDB refuse a second account with the same email, even when two sign-ups arrive at once. The refusal's error code is 11000.
  • Sign-up hashes the password, saves the student and answers 201 Created, or 409 Conflict when the email already has an account.
  • Sign-in gives an unknown email and a wrong password the same 401 and message, so nobody can use it to find out who has an account.
  • Emails are trimmed and lowercased before they're saved or looked up, so Maya@Example.com and maya@example.com are one account.
  • Every response names the fields it sends, never the whole user, so the password hash never leaves the server.

Every sign-up form and sign-in page you've ever filled in sends one of two requests. This lesson writes the server's side of both for Bright Minds Study Group, with the bcrypt hashing from Storing Passwords Safely: Hashing and a users collection in MongoDB. Proving who you are has a name, authentication, and these two routes are where it starts.

One account per email: a unique index

Maya double-clicks Sign up, and two requests arrive a few milliseconds apart. The first try at stopping a second account: look the email up before saving, and refuse it if it's there. But both requests look before either one saves, both find nothing, and both save. Now Maya has two accounts.

The fix is to let the database say no. A unique index on email (an index, as in Indexes and Text Search, with unique: true) makes MongoDB refuse any second document with the same email, however close together they arrive. The refusal is an error with the code 11000. This script deletes the old documents first, so it's safe to run twice:

import { MongoClient } from "mongodb";

const client = await MongoClient.connect(process.env.MONGODB_URI);
const users = client.db("study_group").collection("users");
await users.deleteMany({});
await users.createIndex({ email: 1 }, { unique: true });

await users.insertOne({ name: "Maya", email: "maya@example.com" });
try {
  await users.insertOne({ name: "Maya", email: "maya@example.com" });
} catch (error) {
  console.log(error.code);
  console.log(error.message);
}
await client.close();

With MONGODB_URI=mongodb://localhost:27017 in .env:

node --env-file=.env unique.js
11000
E11000 duplicate key error collection: study_group.users index: email_1 dup key: { email: "maya@example.com" }

Emails need one more step. Maya@Example.com and maya@example.com reach the same inbox, but the index sees two different texts, so the app trims the spaces off every email and lowercases it before saving it or looking it up.

Sign-up: hash, save, answer 201 or 409

The study group keeps its database code in one file, users.js, as Keeping Database Code in One Place does. Its addUser turns the 11000 error into null, so the routes never need MongoDB's error codes:

export async function addUser({ name, email, passwordHash }) {
  try {
    const result = await users.insertOne({ name, email, passwordHash });
    return { id: result.insertedId.toString(), name, email, passwordHash };
  } catch (error) {
    if (error.code === 11000) {
      return null;
    }
    throw error;
  }
}

The sign-up route checks the body, hashes the password and saves the student. Its errors go out through sendProblem, the course's one error shape from Error Handling and Consistent Error Responses, so each one carries a status, a title and a detail:

app.post("/auth/sign-up", async (req, res) => {
  const { name, email, password } = req.body ?? {};
  if (!name || !email || !password || password.length < 8) {
    return sendProblem(res, 400, "Name, email and a password of 8 or more characters are required.");
  }
  const passwordHash = await bcrypt.hash(password, 10);
  const user = await addUser({ name, email: email.trim().toLowerCase(), passwordHash });
  if (user === null) {
    return sendProblem(res, 409, "That email already has an account.");
  }
  res.status(201).json({ id: user.id, name: user.name, email: user.email });
});

Three sign-ups, each request with its answer:

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

POST /auth/sign-up  {"name":"Maya","email":"maya@example.com","password":"another-example-password"}
HTTP/1.1 409 Conflict
{"status":409,"title":"Conflict","detail":"That email already has an account."}

POST /auth/sign-up  {"name":"Leo","email":"leo@example.com","password":"short"}
HTTP/1.1 400 Bad Request
{"status":400,"title":"Bad Request","detail":"Name, email and a password of 8 or more characters are required."}

The second one is refused even though its email's letters are a different case: both became maya@example.com.

Sign-in: one vague answer for every mistake

A helpful sign-in could say There's no account with that email or Wrong password. But then anyone could type a list of emails and learn who's in the study group, and which emails are worth guessing passwords for. So both mistakes get the same answer: 401 Unauthorized, read "you haven't proved who you are", with one message.

app.post("/auth/sign-in", async (req, res) => {
  const { email = "", password = "" } = req.body ?? {};
  const user = await findUserByEmail(email.trim().toLowerCase());
  if (user === null || !(await bcrypt.compare(password, user.passwordHash))) {
    return sendProblem(res, 401, "Wrong email or password.");
  }
  res.json({ id: user.id, name: user.name, email: user.email });
});

The = "" defaults turn a missing field into one more wrong guess. A right password, a wrong one and an unknown email:

POST /auth/sign-in  {"email":"maya@example.com","password":"maya-example-password"}
HTTP/1.1 200 OK
{"id":"6afc93032bca6d42fc88f137","name":"Maya","email":"maya@example.com"}

POST /auth/sign-in  {"email":"maya@example.com","password":"Maya-example-password"}
HTTP/1.1 401 Unauthorized
{"status":401,"title":"Unauthorized","detail":"Wrong email or password."}

POST /auth/sign-in  {"email":"nobody@example.com","password":"maya-example-password"}
HTTP/1.1 401 Unauthorized
{"status":401,"title":"Unauthorized","detail":"Wrong email or password."}

For now, a right password answers with the student. Remembering her, so her next request is known to be hers, is the job of Sessions and Cookies and Tokens: Signing In with a JWT.

The hash never leaves the server

Here's Maya's document, as find() gives it back:

{
  _id: new ObjectId('6afc93032bca6d42fc88f137'),
  name: 'Maya',
  email: 'maya@example.com',
  passwordHash: '$2b$10$UY6fCXoExeSmiJXITvYNDeNrtedbuVErw5EP1Sc4nIySq6m3OVJga'
}

The tempting shortcut is res.json(user). That sends passwordHash to the browser, where anyone can read it, and a hash in an attacker's hands is something to guess against on their own computer, as fast as it allows. So every answer names its fields: { id: user.id, name: user.name, email: user.email }. Logs follow the same rule: log a student signed up and her id, never req.body, which holds her password exactly as she typed it.

Check yourself

2 questions to try on the lesson page.

So what

Sign-up and sign-in are two short routes whose safety is in three details: a unique index, one vague 401, and answers that name their fields.

Key terms

Related