diff --git a/js/app.js b/js/app.js index 24b6a44..5a1bab9 100644 --- a/js/app.js +++ b/js/app.js @@ -811,8 +811,11 @@ async function renderSettingsPage(tab = 'profile') { await API.changePassword(oldPassword, newPassword); document.getElementById('changeOldPassword').value = ''; document.getElementById('changeNewPassword').value = ''; - statusEl.textContent = getIcon('success') + ' 密码修改成功!'; - statusEl.style.color = '#22c55e'; + alert('密码修改成功,所有会话已失效,请重新登录'); + await API.logout(); + currentUser = null; + renderNav(); + switchPage('feed'); } catch (err) { statusEl.textContent = getIcon('error') + ' ' + err.message; statusEl.style.color = '#ef4444'; @@ -835,9 +838,11 @@ async function renderSettingsPage(tab = 'profile') { await API.changeEmail(password, newEmail); document.getElementById('changeEmailPassword').value = ''; document.getElementById('changeNewEmail').value = ''; - currentUser.email = newEmail; - statusEl.textContent = getIcon('success') + ' 邮箱修改成功!'; - statusEl.style.color = '#22c55e'; + alert('邮箱修改成功,所有会话已失效,请使用新邮箱重新登录'); + await API.logout(); + currentUser = null; + renderNav(); + switchPage('feed'); } catch (err) { statusEl.textContent = getIcon('error') + ' ' + err.message; statusEl.style.color = '#ef4444'; diff --git a/schema.sql b/schema.sql index 3e330a7..8e797fc 100644 --- a/schema.sql +++ b/schema.sql @@ -11,6 +11,7 @@ CREATE TABLE IF NOT EXISTS users ( avatar_url TEXT, bio TEXT DEFAULT '', role VARCHAR(10) DEFAULT 'user' CHECK (role IN ('user', 'admin')), + token_version INTEGER NOT NULL DEFAULT 0, 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); 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; -- ============================================================ -- 论坛默认设置 diff --git a/server.js b/server.js index 268e813..8d64627 100644 --- a/server.js +++ b/server.js @@ -13,6 +13,7 @@ const { Pool } = require('pg'); const multer = require('multer'); const path = require('path'); const fs = require('fs'); +const crypto = require('crypto'); 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]; if (!token) { return res.status(401).json({ error: '请先登录' }); } try { 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; next(); } catch (err) { @@ -231,7 +239,7 @@ app.post('/api/auth/login', async (req, res) => { } 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, { expiresIn: '7d' } ); @@ -437,7 +445,10 @@ app.put('/api/users/:id/password', auth, async (req, res) => { } 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 }); } catch (err) { @@ -473,7 +484,10 @@ app.put('/api/users/:id/email', auth, async (req, res) => { 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 }); } catch (err) { @@ -1390,39 +1404,36 @@ app.put('/api/notifications/read-all', auth, async (req, res) => { // 生成随机恢复码 function generateRecoveryCode() { - const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; - let code = ''; - for (let i = 0; i < 20; i++) { - code += chars[Math.floor(Math.random() * chars.length)]; - if (i === 4 || i === 9 || i === 14) code += '-'; - } - return code; + return crypto.randomBytes(12) + .toString('hex') + .toUpperCase() + .match(/.{1,6}/g) + .join('-'); } // 生成 10 个恢复码 app.post('/api/auth/recovery-codes/generate', auth, async (req, res) => { + let client; 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 = []; - const codeHashes = []; - for (let i = 0; i < 10; i++) { - const code = generateRecoveryCode(); - codes.push(code); - const hash = await bcrypt.hash(code, 10); - codeHashes.push(hash); - } - - for (const hash of codeHashes) { - await pool.query( - 'INSERT INTO recovery_codes (user_id, code_hash) VALUES ($1, $2)', - [req.user.id, hash] - ); - } + client = await pool.connect(); + await client.query('BEGIN'); + await client.query('DELETE FROM recovery_codes WHERE user_id = $1', [req.user.id]); + await client.query( + `INSERT INTO recovery_codes (user_id, code_hash) + SELECT $1, code_hash FROM unnest($2::text[]) AS generated(code_hash)`, + [req.user.id, codeHashes] + ); + await client.query('COMMIT'); res.json({ codes }); } catch (err) { + if (client) await client.query('ROLLBACK').catch(() => {}); 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位' }); } + let client; 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) { - return res.status(404).json({ error: '用户不存在' }); + await client.query('ROLLBACK'); + return res.status(400).json({ error: '恢复码无效或已使用' }); } - const codes = await pool.query( - 'SELECT id, code_hash FROM recovery_codes WHERE user_id = $1 AND is_used = false', + const codes = await client.query( + 'SELECT id, code_hash FROM recovery_codes WHERE user_id = $1 AND is_used = false FOR UPDATE', [user.rows[0].id] ); @@ -1474,17 +1489,27 @@ app.post('/api/auth/reset-password', async (req, res) => { } if (!matched) { + await client.query('ROLLBACK'); 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); - 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 }); } catch (err) { + if (client) await client.query('ROLLBACK').catch(() => {}); res.status(500).json({ error: '重置失败,请稍后重试' }); + } finally { + if (client) client.release(); } });