2026-03-12 11:23:10 +08:00
|
|
|
const express = require('express');
|
|
|
|
|
const jwt = require('jsonwebtoken');
|
|
|
|
|
const bcrypt = require('bcryptjs');
|
|
|
|
|
const db = require('../db');
|
2026-03-26 10:39:58 +08:00
|
|
|
const config = require('../config');
|
|
|
|
|
const logger = require('../utils/logger');
|
2026-03-12 11:23:10 +08:00
|
|
|
|
|
|
|
|
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 {
|
2026-03-26 10:39:58 +08:00
|
|
|
req.user = jwt.verify(token, config.jwtSecret);
|
2026-03-12 11:23:10 +08:00
|
|
|
next();
|
|
|
|
|
} catch {
|
|
|
|
|
res.status(401).json({ error: '登录已过期' });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 登录
|
|
|
|
|
router.post('/login', (req, res) => {
|
|
|
|
|
const { username, password } = req.body;
|
2026-03-26 10:39:58 +08:00
|
|
|
|
|
|
|
|
if (!username || !password) {
|
|
|
|
|
return res.status(400).json({ error: '用户名和密码不能为空' });
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-12 11:23:10 +08:00
|
|
|
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
|
|
|
|
|
if (!user || !bcrypt.compareSync(password, user.password)) {
|
2026-03-26 10:39:58 +08:00
|
|
|
logger.warn(`登录失败: ${username}`);
|
2026-03-12 11:23:10 +08:00
|
|
|
return res.status(401).json({ error: '用户名或密码错误' });
|
|
|
|
|
}
|
2026-03-26 10:39:58 +08:00
|
|
|
|
|
|
|
|
const token = jwt.sign({ id: user.id, username: user.username }, config.jwtSecret, { expiresIn: config.jwtExpiresIn });
|
|
|
|
|
logger.info(`用户登录: ${username}`);
|
2026-03-12 11:23:10 +08:00
|
|
|
res.json({ token, username: user.username });
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
module.exports = { router, auth };
|