Menu
CoddyTech

Login Sessions

Part of the Auth and Security section of Coddy's Node.js journey. Lesson 5 of 17.

Login answers 200, then the next request has forgotten who logged in. A session remembers. At login the server makes an id nobody can guess, stores which user it belongs to, and sends it as a cookie. Each later request brings the id back, and the server looks it up.

The id must be random. A cookie holding the username would let anyone type Cookie: sid=ada and be Ada. randomBytes(24) gives 192 random bits. Set the cookie httpOnly so scripts in the page cannot read it.

const cartId = randomBytes(24).toString('base64url');
await carts.insertOne({ _id: cartId, items: [] });
res.cookie('cart', cartId, { httpOnly: true });

// on a later request
const cart = await carts.findOne({ _id: parseCookies(req.get('cookie')).cart });
challenge icon

Challenge

Easy
  • POST /login stores { _id: sid, userId } in sessions and sets the sid cookie, httpOnly, with randomBytes(24).toString('base64url').
  • GET /me answers { username } for that session, or 401 { "error": "Log in first" }.

Sign up, log in, send GET /me, then look at Data.

Try it yourself

import express from 'express';
import { parseCookies } from './cookies.js';
import { notes, users } from './db.js';
import { hashPassword, verifyPassword } from './passwords.js';

const app = express();
app.use(express.json());

app.post('/signup', async (req, res) => {
    const username = String(req.body.username ?? '').trim().toLowerCase();
    const password = String(req.body.password ?? '');
    if (!username || password.length < 8) {
        return res.status(400).json({ error: 'Pick a username and a password of at least 8 characters' });
    }
    if (await users.findOne({ username })) {
        return res.status(409).json({ error: 'That username is taken' });
    }
    await users.insertOne({ username, passwordHash: await hashPassword(password) });
    res.status(201).json({ username });
});

app.post('/login', async (req, res) => {
    const username = String(req.body.username ?? '').trim().toLowerCase();
    const user = await users.findOne({ username });
    if (!user || !(await verifyPassword(String(req.body.password ?? ''), user.passwordHash))) {
        return res.status(401).json({ error: 'Wrong username or password' });
    }
    res.json({ username: user.username });
});

// Counts how many times this browser has called GET /visit.
app.get('/visit', (req, res) => {
    const cookies = parseCookies(req.get('cookie'));
    const visits = Number(cookies.visits ?? 0) + 1;
    res.cookie('visits', String(visits));
    res.json({ visits });
});

// Notes. Anyone can read and write them for now.
app.get('/notes', async (req, res) => {
    res.json(await notes.find().toArray());
});

app.post('/notes', async (req, res) => {
    const note = { text: String(req.body.text ?? '') };
    await notes.insertOne(note);
    res.status(201).json(note);
});

app.listen(3000, () => {
    console.log('Vault is running on port 3000');
});

All lessons in Auth and Security