Start learning free

LESSON 14 OF 58 · FULL-STACK: LOGIN WITH COOKIES

Log In: A Session Cookie

Practice

Each request reaches the server on its own. By itself, the server can't tell that the page asking GET /api/me is the one that logged in a second ago. A session fixes that. The express-session middleware keeps a small object per visitor on the server, req.session, and gives the browser a cookie with that session's id, connect.sid. The browser sends the cookie with every later request, and the middleware finds the same session again.

Whatever you store in req.session is still there on the visitor's next request. With saveUninitialized: false, a visitor gets a cookie only once something is stored. A route that counts one visitor's visits, for example:

app.get("/api/visits", (req, res) => {
  if (req.session.visits === undefined) {
    req.session.visits = 0;
  }
  req.session.visits = req.session.visits + 1;
  res.json({ visits: req.session.visits });
});

To log in, the server finds the user by email and checks the typed password against the stored hash with checkPassword(hash, password), given in server/passwords.js. A wrong email and a wrong password get the same 401 message, so nobody can find out which emails have an account. A good login puts the user's id in the session; GET /api/me reads it back.

The check logs in through the page, reloads it, then sends requests of its own:

POST /api/login {"email": "ana@example.com", "password": "mug-lover-2"}
   →  401  {"error": "Wrong email or password"}
POST /api/login {"email": "ana@example.com", "password": "mug-lover-1"}
   →  200  {"email": "ana@example.com"}
      Set-Cookie: connect.sid=<session id>; Path=/; HttpOnly
GET /api/me  (with that cookie)
   →  200  {"email": "ana@example.com", "id": 1}
GET /api/me  (no cookie)
   →  401  {"error": "Not logged in"}
POST /api/login {"email": "nobody@example.com", "password": "mug-lover-1"}
   →  401  {"error": "Wrong email or password"}

After the reload, the header still says Logged in as ana@example.com.

Your task: in server/app.js, add the session middleware below express.json(). Then add POST /api/login: 401 with "Wrong email or password", or store user.id in req.session.userId and answer the email. Then add GET /api/me: 401 "Not logged in" without a userId, otherwise the user's id and email.


Assignment
Follow the Coding Tutorial to add the session middleware, the login route and the /api/me route.


Hint
Test user === undefined before reading user.password_hash: || stops at the first true part. For /api/me, select only id and email, never the hash.


STEP 1 OF 12
    Ctrl + Enter to check