仅限你查看的笔记
本课属于 Coddy Node.js 学习旅程的“身份验证与安全”单元。第 18 课,共 24 课。
登录只能证明你是谁,不能证明某条笔记属于你。GET /notes/:id只根据笔记的 id 查找笔记,因此任何已登录且知道 id 的人,无论是通过共享链接还是日志得知,都能读取这条笔记。检查所有者称为授权。
在查询本身中加入所有者,这样数据库就不会返回别人的文档。如果找不到笔记,请返回404,而不是 403:403 会告诉访客这条笔记确实存在。
const order = await orders.findOne({
_id: new ObjectId(req.params.id),
customer: req.user.id,
});
if (!order) {
return res.status(404).json({ error: 'Order not found' });
}每个涉及用户数据的查询都需要添加筛选条件,包括读取、更新和删除。
挑战
简单本章回到第 2 章中的会话登录内容,此时服务器已经扩展了功能。现在它有一个位于 GET / 的页面、用于单条笔记的路由 GET /notes/:id 和 DELETE /notes/:id,以及一个管理员账户。这两个 /notes/:id 路由存在漏洞:它们只根据笔记的 ID 查找笔记。任何知道 ID 的已登录用户都可以读取或删除其他人的笔记。修复这个漏洞。
- 在
server.js中的GET /notes/:id里,同时根据笔记的_id和owner查找笔记。所有者必须是已登录用户,也就是req.user.id。 - 在
DELETE /notes/:id中也这样做,这样任何人都无法删除自己不拥有的笔记。 - 没有匹配的笔记时,这两个路由都会以状态码 404 响应,并返回
{"error": "Note not found"}。对于其他人的笔记,也保留这个响应。返回 403 会让访问者知道这条笔记存在。
试试看:按“运行”。
- 发送
POST /signup,然后发送POST /login,两次都使用{"username": "ada", "password": "correct horse"}。 - 使用
{"text": "Safe code 4417"}发送POST /notes,并从响应中复制_id。在GET /notes/后面加上这个 ID,就会返回这条笔记。 - 使用
{"username": "bob", "password": "correct horse"}注册并登录。发送GET /notes/,后面加上 ada 的 ID:状态码为 404,响应为{"error": "Note not found"}。发送DELETE /notes/,后面加上同一个 ID:状态码也为 404。 - 再次以 ada 的身份登录,并使用第一步中的请求体。她的笔记仍然存在。现在对它发送
DELETE:状态码为 204。
亲手试试
import express from 'express';
import { ObjectId } from 'mongodb';
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());
// 唯一的管理员账户,密码来自环境变量。
await users.insertOne({ username: 'admin', role: 'admin', passwordHash: await hashPassword(process.env.ADMIN_PASSWORD) });
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,
sameSite: 'lax',
secure: true,
maxAge: 24 * 60 * 60 * 1000,
});
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, role: user.role };
next();
}
app.get('/me', requireUser, (req, res) => {
res.json({ username: req.user.username });
});
app.post('/logout', async (req, res) => {
const { sid } = parseCookies(req.get('cookie'));
if (sid) {
await sessions.deleteOne({ _id: sid });
}
res.clearCookie('sid');
res.status(204).end();
});
// 将你的笔记显示为页面。
app.get('/', requireUser, async (req, res) => {
const list = await notes.find({ owner: req.user.id }).toArray();
const items = list.map((note) => `<li>${note.text}</li>`).join('');
res.send(`<!doctype html><title>Vault</title><h1>${req.user.username}'s notes</h1><ul>${items}</ul>`);
});
// 笔记:每个用户只能读写自己的笔记。
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.get('/notes/:id', requireUser, async (req, res) => {
if (!ObjectId.isValid(req.params.id)) {
return res.status(404).json({ error: 'Note not found' });
}
const note = await notes.findOne({ _id: new ObjectId(req.params.id) });
if (!note) {
return res.status(404).json({ error: 'Note not found' });
}
res.json(note);
});
app.delete('/notes/:id', requireUser, async (req, res) => {
if (!ObjectId.isValid(req.params.id)) {
return res.status(404).json({ error: 'Note not found' });
}
const { deletedCount } = await notes.deleteOne({ _id: new ObjectId(req.params.id) });
if (!deletedCount) {
return res.status(404).json({ error: 'Note not found' });
}
res.status(204).end();
});
// 供管理员查看:账户总数。
app.get('/admin', requireUser, async (req, res) => {
res.json({ users: await users.countDocuments() });
});
app.listen(3000, () => {
console.log('Vault is running on port 3000');
});
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
身份验证与安全中的所有课
自己练习: Express 在线编辑器