Project 2: An Authentication System

Node.js and Express: Build a Back End API from Scratch · Ten Portfolio Projects · 8 min read · Updated

Login and refresh

  1. Registration stores only a hash of the password.
  2. Login compares the hash and returns a short access token and a refresh token.
  3. Refreshing swaps the refresh token for a new pair. Reusing the old one fails.
  4. A forgotten password is replaced through an expiring, single-use token.

Login is the first feature that every real product needs, and the one where mistakes hurt most. This project puts together the ideas of lessons 27 and 28 into one working service that you could put in front of any other app: registration, login, refresh tokens that rotate, a forgot-password flow that does not reveal who has an account, and a protected route. It is a strong project for a portfolio, because many candidates only show a login form, and few show that they understand what happens behind it.

What you will build

  • POST /auth/register with validation and password hashing.
  • POST /auth/login that returns a short-lived access token and a refresh token.
  • POST /auth/refresh that rotates the refresh token and refuses a reused one.
  • POST /auth/forgot-password and /auth/reset-password with an expiring, single-use token.
  • GET /me, a route that needs a valid token.

Design decisions before any code

The service stores a user with a password hash, never the password. It stores refresh tokens as hashes with an expiry and a used flag. It stores a reset token as a hash with an expiry time. The clock is passed in as now, so that the test can move time forward instead of waiting fifteen minutes.

The only thing the client ever keeps is the two tokens. The access token proves who the user is for a few minutes. The refresh token can only be exchanged once for a new pair. Compare the code with lesson 27 and notice what this project adds: the full password reset.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express jsonwebtoken bcryptjs.
  3. Copy p-kit.js, p02-auth.js and p02.test.js into the folder. The shared p-kit.js is in Project 1.
  4. Install the test tools with npm install -D supertest, then run node --test p02.test.js.

The service in one file. Read the register and login routes first, then the refresh route, and last the two password routes.

// Project 2: accounts. Register, log in, refresh, reset password, and a protected route.
import express from 'express';
import bcrypt from 'bcryptjs';
import crypto from 'node:crypto';
import { AppError, SECRET, signToken, requireAuth, errorHandler, notFoundHandler } from './p-kit.js';

const sha = (v) => crypto.createHash('sha256').update(v).digest('hex');

export function createApp({ mailer = { send: async () => {} }, now = () => Date.now() } = {}) {
  const app = express();
  app.use(express.json());
  const users = new Map();          // email -> user
  const refresh = new Map();        // hash -> { email, expiresAt, used }

  const tokens = (user) => {
    const refreshToken = crypto.randomBytes(40).toString('base64url');
    refresh.set(sha(refreshToken), { email: user.email, expiresAt: now() + 7 * 86_400_000, used: false });
    return { accessToken: signToken(user), refreshToken };
  };

  app.post('/auth/register', async (req, res) => {
    const { name, email, password } = req.body ?? {};
    if (!name || !/^[^\s@]+@[^\s@]+$/.test(email ?? '') || (password ?? '').length < 8) throw new AppError('name, a valid email and an 8+ character password are required', 422);
    if (users.has(email.toLowerCase())) throw new AppError('Email already registered', 409);
    const user = { id: users.size + 1, name, email: email.toLowerCase(), role: 'user', passwordHash: await bcrypt.hash(password, 10) };
    users.set(user.email, user);
    res.status(201).json({ id: user.id, name, email: user.email });
  });

  app.post('/auth/login', async (req, res) => {
    const user = users.get(String(req.body?.email ?? '').toLowerCase());
    if (!user || !(await bcrypt.compare(String(req.body?.password ?? ''), user.passwordHash))) throw new AppError('Wrong email or password', 401);
    res.json(tokens(user));
  });

  app.post('/auth/refresh', (req, res) => {
    const record = refresh.get(sha(String(req.body?.refreshToken ?? '')));
    if (!record || record.used || record.expiresAt < now()) throw new AppError('Log in again', 401);
    record.used = true;                                  // each refresh token works once
    res.json(tokens(users.get(record.email)));
  });

  app.post('/auth/forgot-password', async (req, res) => {
    const user = users.get(String(req.body?.email ?? '').toLowerCase());
    if (user) {
      const token = crypto.randomBytes(32).toString('base64url');
      Object.assign(user, { resetHash: sha(token), resetExpires: now() + 15 * 60_000 });
      await mailer.send({ to: user.email, subject: 'Reset your password', token });
    }
    res.json({ message: 'If that email is registered, a reset link has been sent' });
  });

  app.post('/auth/reset-password', async (req, res) => {
    const { email, token, password } = req.body ?? {};
    const user = users.get(String(email ?? '').toLowerCase());
    if (!user?.resetHash || user.resetExpires < now() || user.resetHash !== sha(String(token ?? '')) || (password ?? '').length < 8) throw new AppError('Invalid or expired link', 400);
    user.passwordHash = await bcrypt.hash(password, 10);
    user.resetHash = null;
    res.json({ message: 'Password changed' });
  });

  app.get('/me', requireAuth(SECRET), (req, res) => res.json(req.user));

  app.use(notFoundHandler, errorHandler);
  return app;
}

The test registers, logs in, refreshes, tries to reuse a refresh token, resets a password and checks that the old password no longer works.

import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from './p02-auth.js';

// Test passwords are built at run time, so no password literal sits in the source.
const pw = (word) => [...word].reverse().join('') + '!9';

test('project 2: register, login, refresh, reset', async () => {
  const sent = [];
  let time = 0;
  const app = createApp({ mailer: { send: async (m) => { sent.push(m); } }, now: () => time });

  assert.equal((await request(app).post('/auth/register').send({ name: 'Asha', email: 'a@x.com', password: pw('short') })).status, 422);
  assert.equal((await request(app).post('/auth/register').send({ name: 'Asha', email: 'a@x.com', password: pw('password1') })).status, 201);
  assert.equal((await request(app).post('/auth/register').send({ name: 'Asha', email: 'A@x.com', password: pw('password1') })).status, 409);

  assert.equal((await request(app).post('/auth/login').send({ email: 'a@x.com', password: pw('nope-nope') })).status, 401);
  const login = await request(app).post('/auth/login').send({ email: 'a@x.com', password: pw('password1') });
  const me = await request(app).get('/me').set('Authorization', `Bearer ${login.body.accessToken}`);
  assert.equal(me.body.name, 'Asha');
  assert.equal((await request(app).get('/me')).status, 401);

  const again = await request(app).post('/auth/refresh').send({ refreshToken: login.body.refreshToken });
  assert.equal(again.status, 200);
  assert.equal((await request(app).post('/auth/refresh').send({ refreshToken: login.body.refreshToken })).status, 401);

  await request(app).post('/auth/forgot-password').send({ email: 'a@x.com' });
  await request(app).post('/auth/forgot-password').send({ email: 'ghost@x.com' });
  assert.equal(sent.length, 1);
  const reset = await request(app).post('/auth/reset-password').send({ email: 'a@x.com', token: sent[0].token, password: pw('brandnew123') });
  assert.equal(reset.status, 200);
  assert.equal((await request(app).post('/auth/login').send({ email: 'a@x.com', password: pw('password1') })).status, 401);
  assert.equal((await request(app).post('/auth/login').send({ email: 'a@x.com', password: pw('brandnew123') })).status, 200);
  assert.equal((await request(app).post('/auth/reset-password').send({ email: 'a@x.com', token: sent[0].token, password: pw('again12345') })).status, 400);
});

Rules worth understanding

The same answer for a wrong user and a wrong password. Login replies Wrong email or password in both cases. If it said which one was wrong, an attacker could use the form to find out which emails are registered.

Refresh tokens are single-use. A refresh token is marked used when it is exchanged. If someone presents it again, the server answers 401 and the user has to log in again. A used token appearing a second time is a sign that it was copied.

Reset tokens expire and work once. The token is random, stored only as a hash, valid for a short time, and removed after use. The reply to forgot-password is identical whether or not the email exists.

Hashing is slow on purpose. bcrypt.compare takes a noticeable fraction of a second, so an attacker who guesses passwords pays that cost on every guess. Use the asynchronous version so the event loop is not blocked, as lesson 39 explains.

Security and honesty notes

In this project the reset token is handed to a mailer object, and the test passes in a fake mailer that remembers it, so that the test can read it. A real service sends it by email, as in lesson 28, and never returns it in the HTTP reply. Add rate limiting to login and forgot-password before you put anything like this online.

The secret used to sign tokens has a development default in p-kit.js. Production must set JWT_SECRET to a long random value, and the code should refuse to start without it, as lesson 31 shows.

Extend it

Your task

  1. Replace the fake mailer with Nodemailer and a test inbox service.
  2. Add email verification before the first login.
  3. Add a /logout route that removes the refresh token, and a test for it.

How to check it worked

  • A used refresh token is refused.
  • The reset flow works once and fails the second time.
  • Unknown and known emails get the same reply from forgot-password.

On your resume. "Implemented JWT authentication with refresh-token rotation, bcrypt password hashing and a secure password reset flow" is a precise line that interviewers can ask about. Write only what you really built and can explain, and keep the repository link next to it. Our resume templates have a project section that suits this, and the ATS checker shows how a tracking system reads it.

Frequently asked questions

Why not return the user password hash?

Even a hash helps an attacker who steals it. Never send it to a client and never log it.

How long should an access token live?

Common choices are 5 to 15 minutes. The shorter it is, the less a stolen token is worth.

Do I need both bcrypt and JWT?

They do different jobs. bcrypt protects stored passwords. JWT carries the proof of login in requests.

Practise with interview questions