Menu
CoddyTech

退出登录

本课属于 Coddy Node.js 学习旅程的“身份验证与安全”单元。第 12 课,共 24 课。

清除 Cookie 只是让浏览器忘记这个 id。任何复制了该 id 的人,无论是从共用电脑上复制的,还是从被盗的 Cookie 中复制的,仍然持有一把有效的钥匙。退出登录时,必须删除服务器上的会话。

res.clearCookie(name) 会让浏览器删除 Cookie。状态码 204 No Content 表示操作成功,而且没有内容需要发送回来:res.status(204).end()。

下面是一个相关路由,可以让用户同时在所有设备上退出登录:

app.post('/logout-everywhere', requireUser, async (req, res) => {
    await sessions.deleteMany({ userId: new ObjectId(req.user.id) });
    res.clearCookie('sid');
    res.status(204).end();
});
challenge icon

挑战

简单

添加注销功能。仅删除 Cookie 还不够,因为任何复制了会话 ID 的人都可以继续使用它。因此,服务器也会删除会话。

  1. 在 server.js 中添加 POST /logout。它不需要请求体。
  2. 读取 sid Cookie。如果有这个 Cookie,就从 sessions 中删除具有该 _id 的会话。
  3. 让浏览器删除 sid Cookie。
  4. 返回状态码 204,不带请求体。204 无内容表示操作成功,并且没有内容需要发回。即使请求中没有 sid Cookie,也要返回 204。

试试看:点击“运行”。发送 POST /signup,然后发送 POST /login,两者都使用 {"username": "ada", "password": "correct horse"}。GET /me 会返回 {"username": "ada"}。发送 POST /logout:状态码为 204,且响应体为空。再次发送 GET /me:状态码为 401,并返回 {"error": "Log in first"}。打开“数据”:sessions 为空。再发送一次 POST /logout:仍然返回 204。

亲手试试

import express from 'express';
import { randomBytes } from 'node:crypto';
import { parseCookies } from './cookies.js';
import { notes, sessions, 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' });
    }
    const sid = randomBytes(24).toString('base64url');
    await sessions.insertOne({ _id: sid, userId: user._id, createdAt: new Date() });
    res.cookie('sid', sid, { httpOnly: true });
    res.json({ username: user.username });
});

// 查找会话 cookie 对应的用户,找不到则返回 401。
async function requireUser(req, res, next) {
    const { sid } = parseCookies(req.get('cookie'));
    const session = sid && (await sessions.findOne({ _id: sid }));
    const user = session && (await users.findOne({ _id: session.userId }));
    if (!user) {
        return res.status(401).json({ error: 'Log in first' });
    }
    req.user = { id: user._id.toHexString(), username: user.username };
    next();
}

app.get('/me', requireUser, (req, res) => {
    res.json({ username: req.user.username });
});

// 统计此浏览器调用 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 });
});

// 笔记:每个用户只能读写自己的笔记。
app.get('/notes', requireUser, async (req, res) => {
    res.json(await notes.find({ owner: req.user.id }).toArray());
});

app.post('/notes', requireUser, async (req, res) => {
    const note = { owner: req.user.id, 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');
});

身份验证与安全中的所有课

自己练习: Express 在线编辑器