// 登录、登出、当前用户、修改密码
import { Router } from 'express';
import bcrypt from 'bcryptjs';
import { db } from '../db.js';
import { getClientSettings } from '../settings.js';
import { createSession, destroySession, requireAuth, publicUser } from '../auth.js';
const router = Router();
// 简单的登录失败限流(内存级,重启后重置)
const attempts = new Map();
const MAX_FAILS = 10;
const WINDOW = 10 * 60 * 1000;
function checkLimit(ip) {
const item = attempts.get(ip);
if (!item) return true;
if (Date.now() - item.ts > WINDOW) {
attempts.delete(ip);
return true;
}
return item.count < MAX_FAILS;
}
function markFail(ip) {
const item = attempts.get(ip) || { count: 0, ts: Date.now() };
item.count += 1;
item.ts = Date.now();
attempts.set(ip, item);
}
router.post('/login', (req, res) => {
const ip = req.ip || 'unknown';
if (!checkLimit(ip)) return res.status(429).json({ error: '登录失败次数过多,请稍后再试' });
const username = String(req.body?.username || '').trim();
const password = String(req.body?.password || '');
if (!username || !password) return res.status(400).json({ error: '请输入用户名和密码' });
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
if (!user || !bcrypt.compareSync(password, user.password_hash)) {
markFail(ip);
return res.status(401).json({ error: '用户名或密码错误' });
}
if (user.disabled) return res.status(403).json({ error: '该账号已被停用,请联系管理员' });
attempts.delete(ip);
createSession(res, user.id);
res.json({ user: publicUser(user), settings: getClientSettings(user.id) });
});
router.post('/logout', (req, res) => {
destroySession(req, res);
res.json({ ok: true });
});
router.get('/me', requireAuth, (req, res) => {
res.json({ user: publicUser(req.user), settings: getClientSettings(req.user.id) });
});
router.post('/password', requireAuth, (req, res) => {
const current = String(req.body?.currentPassword || '');
const next = String(req.body?.newPassword || '');
if (!bcrypt.compareSync(current, req.user.password_hash)) {
return res.status(400).json({ error: '当前密码不正确' });
}
if (next.length < 6) return res.status(400).json({ error: '新密码至少 6 位' });
db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(
bcrypt.hashSync(next, 10),
req.user.id
);
// 其他设备上的会话失效,保留当前会话
if (req.sessionToken) {
db.prepare('DELETE FROM sessions WHERE user_id = ? AND token != ?').run(
req.user.id,
req.sessionToken
);
}
res.json({ ok: true });
});
export default router;