1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| const express = require('express'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const { Users } = require('../MySQL/db'); const router = express.Router();
const SALT_ROUNDS = 10; const SECRET_KEY = process.env.SERVER_TOOLS_LOGIN_SECRET;
if (!SECRET_KEY) { throw new Error('缺少 JWT 密钥,请检查环境变量配置'); }
router.post('/register', async (req, res) => { const { username, password, role } = req.body; if (!username || !password) { return res.status(400).json({ success: false, message: '用户名和密码不能为空' }); }
try { const exists = await Users.findOne({ where: { username } }); if (exists) { return res.status(409).json({ success: false, message: '用户名已存在' }); }
const hash = await bcrypt.hash(password, SALT_ROUNDS); const newUser = await Users.create({ username, password: hash, role: role || 'user' });
res.json({ code: 20000, success: true, message: '注册成功', userId: newUser.id }); } catch (err) { console.error('注册出错:', err); res.status(500).json({ success: false, message: '服务器错误' }); } });
router.post('/login', async (req, res) => { const { username, password } = req.body; if (!username || !password) { return res.status(400).json({ success: false, message: '用户名和密码不能为空' }); }
try { const user = await Users.findOne({ where: { username } }); if (!user) { return res.status(401).json({ success: false, message: '用户名不存在' }); }
const valid = await bcrypt.compare(password, user.password); if (!valid) { return res.status(401).json({ success: false, message: '密码错误' }); }
const token = jwt.sign({ id: user.id, role: user.role }, SECRET_KEY, { expiresIn: '7d' });
res.json({ code: 20000, success: true, message: '登录成功', token, user: { id: user.id, username: user.username, role: user.role } }); } catch (err) { console.error('登录出错:', err); res.status(500).json({ success: false, message: '服务器错误' }); } });
module.exports = router;
|