Files
department-api/routes/auth.js
huanglinhuan aaee847593 init commit
2025-12-03 22:20:43 +08:00

91 lines
2.4 KiB
JavaScript
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('../middleware/auth');
const router = express.Router();
// 模拟用户数据库(实际项目中应使用真实数据库)
const users = [
{
id: 1,
username: 'admin',
password: '$2a$10$rOzJqJqJqJqJqJqJqJqJqOqJqJqJqJqJqJqJqJqJqJqJqJqJqJq', // password: admin123
name: '管理员'
}
];
// 初始化默认用户密码admin123
async function initDefaultUser() {
const hashedPassword = await bcrypt.hash('admin123', 10);
users[0].password = hashedPassword;
}
initDefaultUser();
// 登录接口
router.post('/login', async (req, res) => {
try {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: '用户名和密码不能为空' });
}
// 查找用户
const user = users.find(u => u.username === username);
if (!user) {
return res.status(401).json({ error: '用户名或密码错误' });
}
// 验证密码
const isValidPassword = await bcrypt.compare(password, user.password);
if (!isValidPassword) {
return res.status(401).json({ error: '用户名或密码错误' });
}
// 生成JWT token
const token = jwt.sign(
{ id: user.id, username: user.username, name: user.name },
JWT_SECRET,
{ expiresIn: '24h' }
);
res.json({
success: true,
token,
user: {
id: user.id,
username: user.username,
name: user.name
}
});
} catch (error) {
console.error('登录错误:', error);
res.status(500).json({ error: '服务器内部错误' });
}
});
// 验证token接口
router.get('/verify', async (req, res) => {
try {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: '未提供访问令牌' });
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({ error: '无效的访问令牌' });
}
res.json({ success: true, user });
});
} catch (error) {
res.status(500).json({ error: '服务器内部错误' });
}
});
module.exports = router;