33 lines
1.0 KiB
JavaScript
33 lines
1.0 KiB
JavaScript
const express = require('express');
|
|
const jwt = require('jsonwebtoken');
|
|
const bcrypt = require('bcryptjs');
|
|
const db = require('../db');
|
|
|
|
const router = express.Router();
|
|
const SECRET = 'gamer-order-secret-2024';
|
|
|
|
// 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, SECRET);
|
|
next();
|
|
} catch {
|
|
res.status(401).json({ error: '登录已过期' });
|
|
}
|
|
}
|
|
|
|
// 登录
|
|
router.post('/login', (req, res) => {
|
|
const { username, password } = req.body;
|
|
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
|
|
if (!user || !bcrypt.compareSync(password, user.password)) {
|
|
return res.status(401).json({ error: '用户名或密码错误' });
|
|
}
|
|
const token = jwt.sign({ id: user.id, username: user.username }, SECRET, { expiresIn: '7d' });
|
|
res.json({ token, username: user.username });
|
|
});
|
|
|
|
module.exports = { router, auth };
|