Ordering 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 FastAPI dependencies that know 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
  • Python
  • In the all labs plan

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

Why you need this

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

HTTP/1.1 200 OK
date: Sat, 24 Oct 2026 03:40:29 GMT
content-length: 88
content-type: application/json

{"user":{"id":2,"email":"tara.shetty@example.com","name":"Tara Shetty","role":"member"}}

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

Bhavna needs more than a name, too. From chapter 5 she opens kitchens, changes menus and plans slots through /admin routes, and a member must not: Farah does not want any member closing the 12:30 Goregaon slot in launch week because a route forgot to ask who they are. So every request must 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.py: sign and check a token

    Write two functions in app/lib/jwt.py with PyJWT (imported as jwt). sign_token(sub, role) returns a JWT signed with HS256 and settings.jwt_secret whose payload has "sub", the user's id as a string ("2"), "role", "iat", now in whole seconds (int(time.time())), and "exp", TOKEN_DAYS (7) days later, so exp minus iat is 604800.

    verify_token(token) returns TokenClaims(sub, role) for a token this API signed, with sub an int again (2), and None for anything else, without ever raising: a payload changed by hand, another secret, an expired token, alg none, a token with no exp, a sub that is not a number, a role that is not member or admin, or text that is not a token.

    The Check reads your token's header and payload, verifies it with settings.jwt_secret, and tries verify_token on each of those bad tokens.

  2. Task 2

    auth.py: current_user and require_role

    Write two FastAPI dependencies in app/core/auth.py. current_user(request) reads the cookie SESSION_COOKIE (dabba_session) from request.cookies and checks it with verify_token. With no cookie it raises unauthorized("Log in first"); with a cookie that does not verify, unauthorized("Your session has expired: log in again"). Both are 401 with the code unauthorized. For a valid token it makes CurrentUser(id=claims.sub, role=claims.role), puts it on request.state.user and returns it.

    require_role(*roles) returns a dependency that itself depends on current_user (Depends(current_user)), raises forbidden(...) (403, code forbidden, any message) when the user's role is not one of roles, and returns the user when it is.

    The Check runs them on a tiny app of its own with the project's error handlers (no cookie, a bad cookie, Tara's and Bhavna's tokens, require_role("admin") and require_role("member", "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: router.py, the session cookie

    In app/modules/auth/router.py, fill in COOKIE, the cookie's settings: "path" "/", "httponly" True, "samesite" "lax", "secure" settings.production. Write set_session(response, user): response.set_cookie(SESSION_COOKIE, sign_token(user["id"], user["role"]), max_age=TOKEN_DAYS days in seconds (604800), **COOKIE). signup (201 { "user" }) and login (200 { "user" }) call it before they answer.

    logout clears the cookie with response.delete_cookie(SESSION_COOKIE, **COOKIE) and answers 204 with no body. me depends on current_user, reads the person again with service.find_user and answers 200 { "user" }; when find_user finds no one, it raises unauthorized("Your account no longer exists").

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

    Kunal will ask: why does DabbaDrop keep the token in an httpOnly cookie instead of sending it in the JSON for the app 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.
  • PyJWT: jwt.encode with a secret and an expiry, jwt.decode that trusts nothing else, and its errors.
  • Cookies: set-cookie and its settings, HttpOnly, SameSite, Secure, Max-Age, Path, and deleting one.
  • Dependencies that guard a route: current_user finds the person, require_role checks the role.
  • 401 and 403: who are you, and you may not.

More in Accounts

Build "Sessions and roles" yourself

DabbaDrop delivers tiffins across Mumbai. You build its ordering 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 Ordering backend project are free. This one comes with the all labs plan.