Make account recovery atomic and session aware

This commit is contained in:
Arun committed 2026-08-11 09:44:39 +00:00
1 parent 145f13fee5
commit 2e12468293
3 files changed
+70 -38

No files matched your search

+10 -5
View File
@@ -811,8 +811,11 @@ async function renderSettingsPage(tab = 'profile') {
await API.changePassword(oldPassword, newPassword); await API.changePassword(oldPassword, newPassword);
document.getElementById('changeOldPassword').value = ''; document.getElementById('changeOldPassword').value = '';
document.getElementById('changeNewPassword').value = ''; document.getElementById('changeNewPassword').value = '';
statusEl.textContent = getIcon('success') + ' 密码修改成功!'; alert('密码修改成功,所有会话已失效,请重新登录');
statusEl.style.color = '#22c55e'; await API.logout();
currentUser = null;
renderNav();
switchPage('feed');
} catch (err) { } catch (err) {
statusEl.textContent = getIcon('error') + ' ' + err.message; statusEl.textContent = getIcon('error') + ' ' + err.message;
statusEl.style.color = '#ef4444'; statusEl.style.color = '#ef4444';
@@ -835,9 +838,11 @@ async function renderSettingsPage(tab = 'profile') {
await API.changeEmail(password, newEmail); await API.changeEmail(password, newEmail);
document.getElementById('changeEmailPassword').value = ''; document.getElementById('changeEmailPassword').value = '';
document.getElementById('changeNewEmail').value = ''; document.getElementById('changeNewEmail').value = '';
currentUser.email = newEmail; alert('邮箱修改成功,所有会话已失效,请使用新邮箱重新登录');
statusEl.textContent = getIcon('success') + ' 邮箱修改成功!'; await API.logout();
statusEl.style.color = '#22c55e'; currentUser = null;
renderNav();
switchPage('feed');
} catch (err) { } catch (err) {
statusEl.textContent = getIcon('error') + ' ' + err.message; statusEl.textContent = getIcon('error') + ' ' + err.message;
statusEl.style.color = '#ef4444'; statusEl.style.color = '#ef4444';
+2
View File
@@ -11,6 +11,7 @@ CREATE TABLE IF NOT EXISTS users (
avatar_url TEXT, avatar_url TEXT,
bio TEXT DEFAULT '', bio TEXT DEFAULT '',
role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')), role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')),
token_version INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT now() created_at TIMESTAMPTZ DEFAULT now()
); );
@@ -201,6 +202,7 @@ ALTER TABLE posts ADD COLUMN IF NOT EXISTS pinned_at TIMESTAMPTZ;
CREATE INDEX IF NOT EXISTS idx_posts_is_pinned ON posts(is_pinned); CREATE INDEX IF NOT EXISTS idx_posts_is_pinned ON posts(is_pinned);
ALTER TABLE users ADD COLUMN IF NOT EXISTS signature TEXT DEFAULT ''; ALTER TABLE users ADD COLUMN IF NOT EXISTS signature TEXT DEFAULT '';
ALTER TABLE users ADD COLUMN IF NOT EXISTS token_version INTEGER NOT NULL DEFAULT 0;
-- ============================================================ -- ============================================================
-- 论坛默认设置 -- 论坛默认设置
+58 -33
View File
@@ -13,6 +13,7 @@ const { Pool } = require('pg');
const multer = require('multer'); const multer = require('multer');
const path = require('path'); const path = require('path');
const fs = require('fs'); const fs = require('fs');
const crypto = require('crypto');
const app = express(); const app = express();
@@ -92,13 +93,20 @@ app.use('/uploads', express.static(path.join(__dirname, 'uploads'), {
// ============================================================ // ============================================================
// 认证中间件 // 认证中间件
// ============================================================ // ============================================================
const auth = (req, res, next) => { const auth = async (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1]; const token = req.headers.authorization?.split(' ')[1];
if (!token) { if (!token) {
return res.status(401).json({ error: '请先登录' }); return res.status(401).json({ error: '请先登录' });
} }
try { try {
const decoded = jwt.verify(token, JWT_SECRET); const decoded = jwt.verify(token, JWT_SECRET);
const current = await pool.query(
'SELECT token_version FROM users WHERE id = $1',
[decoded.id]
);
if (!current.rows[0] || decoded.token_version !== current.rows[0].token_version) {
return res.status(401).json({ error: '登录已失效,请重新登录' });
}
req.user = decoded; req.user = decoded;
next(); next();
} catch (err) { } catch (err) {
@@ -231,7 +239,7 @@ app.post('/api/auth/login', async (req, res) => {
} }
const token = jwt.sign( const token = jwt.sign(
{ id: user.id, email: user.email, role: user.role }, { id: user.id, email: user.email, role: user.role, token_version: user.token_version },
JWT_SECRET, JWT_SECRET,
{ expiresIn: '7d' } { expiresIn: '7d' }
); );
@@ -437,7 +445,10 @@ app.put('/api/users/:id/password', auth, async (req, res) => {
} }
const hash = await bcrypt.hash(newPassword, 10); const hash = await bcrypt.hash(newPassword, 10);
await pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, userId]); await pool.query(
'UPDATE users SET password_hash = $1, token_version = token_version + 1 WHERE id = $2',
[hash, userId]
);
res.json({ success: true }); res.json({ success: true });
} catch (err) { } catch (err) {
@@ -473,7 +484,10 @@ app.put('/api/users/:id/email', auth, async (req, res) => {
return res.status(400).json({ error: '邮箱已被占用' }); return res.status(400).json({ error: '邮箱已被占用' });
} }
await pool.query('UPDATE users SET email = $1 WHERE id = $2', [newEmail, userId]); await pool.query(
'UPDATE users SET email = $1, token_version = token_version + 1 WHERE id = $2',
[newEmail, userId]
);
res.json({ success: true }); res.json({ success: true });
} catch (err) { } catch (err) {
@@ -1390,39 +1404,36 @@ app.put('/api/notifications/read-all', auth, async (req, res) => {
// 生成随机恢复码 // 生成随机恢复码
function generateRecoveryCode() { function generateRecoveryCode() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; return crypto.randomBytes(12)
let code = ''; .toString('hex')
for (let i = 0; i < 20; i++) { .toUpperCase()
code += chars[Math.floor(Math.random() * chars.length)]; .match(/.{1,6}/g)
if (i === 4 || i === 9 || i === 14) code += '-'; .join('-');
}
return code;
} }
// 生成 10 个恢复码 // 生成 10 个恢复码
app.post('/api/auth/recovery-codes/generate', auth, async (req, res) => { app.post('/api/auth/recovery-codes/generate', auth, async (req, res) => {
let client;
try { try {
await pool.query('DELETE FROM recovery_codes WHERE user_id = $1', [req.user.id]); const codes = Array.from({ length: 10 }, generateRecoveryCode);
const codeHashes = await Promise.all(codes.map(code => bcrypt.hash(code, 10)));
const codes = []; client = await pool.connect();
const codeHashes = []; await client.query('BEGIN');
for (let i = 0; i < 10; i++) { await client.query('DELETE FROM recovery_codes WHERE user_id = $1', [req.user.id]);
const code = generateRecoveryCode(); await client.query(
codes.push(code); `INSERT INTO recovery_codes (user_id, code_hash)
const hash = await bcrypt.hash(code, 10); SELECT $1, code_hash FROM unnest($2::text[]) AS generated(code_hash)`,
codeHashes.push(hash); [req.user.id, codeHashes]
}
for (const hash of codeHashes) {
await pool.query(
'INSERT INTO recovery_codes (user_id, code_hash) VALUES ($1, $2)',
[req.user.id, hash]
); );
} await client.query('COMMIT');
res.json({ codes }); res.json({ codes });
} catch (err) { } catch (err) {
if (client) await client.query('ROLLBACK').catch(() => {});
res.status(500).json({ error: '生成恢复码失败' }); res.status(500).json({ error: '生成恢复码失败' });
} finally {
if (client) client.release();
} }
}); });
@@ -1450,14 +1461,18 @@ app.post('/api/auth/reset-password', async (req, res) => {
return res.status(400).json({ error: '密码至少6位' }); return res.status(400).json({ error: '密码至少6位' });
} }
let client;
try { try {
const user = await pool.query('SELECT id FROM users WHERE email = $1', [email]); client = await pool.connect();
await client.query('BEGIN');
const user = await client.query('SELECT id FROM users WHERE LOWER(email) = LOWER($1)', [email]);
if (user.rows.length === 0) { if (user.rows.length === 0) {
return res.status(404).json({ error: '用户不存在' }); await client.query('ROLLBACK');
return res.status(400).json({ error: '恢复码无效或已使用' });
} }
const codes = await pool.query( const codes = await client.query(
'SELECT id, code_hash FROM recovery_codes WHERE user_id = $1 AND is_used = false', 'SELECT id, code_hash FROM recovery_codes WHERE user_id = $1 AND is_used = false FOR UPDATE',
[user.rows[0].id] [user.rows[0].id]
); );
@@ -1474,17 +1489,27 @@ app.post('/api/auth/reset-password', async (req, res) => {
} }
if (!matched) { if (!matched) {
await client.query('ROLLBACK');
return res.status(400).json({ error: '恢复码无效或已使用' }); return res.status(400).json({ error: '恢复码无效或已使用' });
} }
await pool.query('UPDATE recovery_codes SET is_used = true WHERE id = $1', [matchedId]);
const hash = await bcrypt.hash(newPassword, 10); const hash = await bcrypt.hash(newPassword, 10);
await pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, user.rows[0].id]); await client.query(
'UPDATE recovery_codes SET is_used = true WHERE id = $1 AND is_used = false',
[matchedId]
);
await client.query(
'UPDATE users SET password_hash = $1, token_version = token_version + 1 WHERE id = $2',
[hash, user.rows[0].id]
);
await client.query('COMMIT');
res.json({ success: true }); res.json({ success: true });
} catch (err) { } catch (err) {
if (client) await client.query('ROLLBACK').catch(() => {});
res.status(500).json({ error: '重置失败,请稍后重试' }); res.status(500).json({ error: '重置失败,请稍后重试' });
} finally {
if (client) client.release();
} }
}); });