Booking backend project · Chapter 4 of 12

Sessions and roles

By the end of this chapter you can keep a person logged in across requests with a signed token (a JWT) in an httpOnly cookie, protect routes with middleware that knows who is asking, let only admins through where admins belong, and say why the cookie, not the browser's localStorage, holds the token. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Accounts
  • 3 tasks
  • TypeScript
  • In the all labs plan

The first 2 chapters of Booking backend project are free. This one comes with the all labs plan.

Why you need this

Chapter 3's login checks Neha's password and answers 200 with her name. Then it forgets her. HTTP has no memory: the next request, "hold seat E7 for me", arrives with nothing that says who sent it. Look at what the login answers today:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 88

{"user":{"id":2,"email":"neha.bapat1005@example.com","name":"Neha Bapat","role":"user"}}

No Set-Cookie, so the browser has nothing to send back. The request pane has the same problem: its personas, "Asha (admin)" and "Neha (member)", log in once and reuse the cookie the login set. With no cookie, sending as a persona stops with "Logging in as Asha (admin) answered 200: does your login route work yet?".

Asha needs more than a name, too. From chapter 5 she adds venues, shows and showtimes through /admin routes, and a member must not: Sayali does not want any of Parda's 600 members cancelling Diwali showtimes because a route forgot to ask who they are. So every request needs to carry proof of who sent it, the proof must be impossible to fake, and some routes must check the role inside it.

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    jwt.ts: sign and check a token

    Write two functions in src/lib/jwt.ts with jsonwebtoken (imported as jwt). signToken({ sub, role }) returns a JWT signed with HS256 and config.jwtSecret: its payload has role, the subject sub as the user's id in a string ("2"), and an expiry TOKEN_DAYS (7) days later, so exp minus iat is 604800.

    verifyToken(token) returns { sub, role } for a token this API signed, with sub as a number again (2), and null for anything else, without ever throwing: a payload changed by hand, another secret, an expired token, alg none, a role that is not user or admin, or text that is not a token.

    The Check reads your token's header and payload, verifies it with config.jwtSecret, and tries verifyToken on each of those bad tokens.

  2. Task 2

    auth.ts: requireAuth and requireRole

    Write two Express middlewares in src/middleware/auth.ts. requireAuth(req, res, next) reads the cookie SESSION_COOKIE (parda_session) from req.cookies and checks it with verifyToken. For a valid token it puts { id, role } in res.locals.user (id is the token's sub) and calls next(). With no cookie it calls next(unauthorized('Log in first')); with a cookie that does not verify, next(unauthorized('Your session has expired: log in again')). Both are 401 with the code unauthorized.

    requireRole(...roles) returns a middleware for after requireAuth: next() when res.locals.user's role is one of roles, next(forbidden(...)) for another role (403, code forbidden, any message), and next(unauthorized('Log in first')) when there is no res.locals.user.

    The Check runs them on a tiny app of its own with the project's error handler (no cookie, a bad cookie, Neha's and Asha's tokens, requireRole('admin') and requireRole('user', 'admin')), then sends GET /auth/me to the real app signed out and with a token signed by another secret: both 401.

  3. Task 3 · interview question

    Interview: auth.controller.ts, the session cookie

    In src/modules/auth/auth.controller.ts, fill in sessionCookie, the cookie's options: httpOnly true, sameSite 'lax', secure config.production, path '/', and maxAge TOKEN_DAYS days in milliseconds (604800000). signupHandler (201 { user }) and loginHandler (200 { user }) also set the cookie SESSION_COOKIE to signToken({ sub: user.id, role: user.role }) with those options.

    logoutHandler clears the cookie with the same options without maxAge and answers 204 with no body. meHandler runs after requireAuth: it reads the person in res.locals.user again with findUser and answers 200 { user }; when findUser finds no one, it throws unauthorized('Your account no longer exists').

    The Check logs in as Neha and reads the Set-Cookie line (HttpOnly, SameSite=Lax, Path=/, Max-Age=604800, no Secure in the lab, a token for Neha), sends GET /auth/me with that cookie, logs out (204, the cookie cleared with Path=/) and wants GET /auth/me to be 401 afterwards. Asha's /auth/me says admin, a signup sets the cookie too, and a deleted account's cookie gets that 401.

    Nikhil will ask: why does Parda keep the token in an httpOnly cookie instead of sending it in the JSON for the React site to keep in localStorage?

What you will learn

  • JWTs: a signed token that says who you are; its three parts; what the signature protects and what it does not hide.
  • jsonwebtoken: signing with a secret and an expiry, and verifying without trusting anything else.
  • Cookies: Set-Cookie and its options, httpOnly, sameSite, secure, maxAge, path, and clearing one.
  • Middleware that guards a route: requireAuth puts the person in res.locals, requireRole checks the role.
  • 401 and 403: who are you, and you may not.

More in Accounts

Build "Sessions and roles" yourself

Parda sells tickets for Pune's own cinemas and stages. You build its booking API, one module a chapter, and take the whole codebase home. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Booking backend project are free. This one comes with the all labs plan.