主要改进: - 新增配置管理 (server/config.js) - 新增日志工具 (server/utils/logger.js) - 添加全局错误处理中间件,统一错误响应格式 - 添加输入验证和 AppError 错误类 - 重构 db.js 迁移逻辑,代码更清晰 - 前端列表改为无限滚动加载,每页 20 条 - 封装 AppState 状态管理模块 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
42 lines
1.3 KiB
JavaScript
42 lines
1.3 KiB
JavaScript
const express = require('express');
|
|
const jwt = require('jsonwebtoken');
|
|
const bcrypt = require('bcryptjs');
|
|
const db = require('../db');
|
|
const config = require('../config');
|
|
const logger = require('../utils/logger');
|
|
|
|
const router = express.Router();
|
|
|
|
// JWT 中间件
|
|
function auth(req, res, next) {
|
|
const token = req.headers.authorization?.split(' ')[1];
|
|
if (!token) return res.status(401).json({ error: '未登录' });
|
|
try {
|
|
req.user = jwt.verify(token, config.jwtSecret);
|
|
next();
|
|
} catch {
|
|
res.status(401).json({ error: '登录已过期' });
|
|
}
|
|
}
|
|
|
|
// 登录
|
|
router.post('/login', (req, res) => {
|
|
const { username, password } = req.body;
|
|
|
|
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)) {
|
|
logger.warn(`登录失败: ${username}`);
|
|
return res.status(401).json({ error: '用户名或密码错误' });
|
|
}
|
|
|
|
const token = jwt.sign({ id: user.id, username: user.username }, config.jwtSecret, { expiresIn: config.jwtExpiresIn });
|
|
logger.info(`用户登录: ${username}`);
|
|
res.json({ token, username: user.username });
|
|
});
|
|
|
|
module.exports = { router, auth };
|