ADD file via upload

main
phgkfux43 4 months ago
parent dc8039b6c1
commit 6e033c053a

@ -0,0 +1,67 @@
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const { jwtSecret } = require('../config');
// 用户注册
exports.register = async (req, res, next) => {
try {
const { username, password, role } = req.body;
// 检查用户名是否存在
const existingUser = await User.findOne({ username });
if (existingUser) {
return res.status(400).json({ message: 'Username already exists' });
}
// 创建新用户
const user = new User({ username, password, role });
await user.save();
// 生成JWT
const token = jwt.sign({ id: user._id, role: user.role }, jwtSecret, {
expiresIn: '1h'
});
res.status(201).json({ token, user: { id: user._id, username: user.username, role: user.role } });
} catch (err) {
next(err);
}
};
// 用户登录
exports.login = async (req, res, next) => {
try {
const { username, password } = req.body;
// 查找用户
const user = await User.findOne({ username });
if (!user) {
return res.status(401).json({ message: 'Invalid credentials' });
}
// 验证密码
const isMatch = await user.comparePassword(password);
if (!isMatch) {
return res.status(401).json({ message: 'Invalid credentials' });
}
// 生成JWT
const token = jwt.sign({ id: user._id, role: user.role }, jwtSecret, {
expiresIn: '1h'
});
res.json({ token, user: { id: user._id, username: user.username, role: user.role } });
} catch (err) {
next(err);
}
};
// 获取当前用户信息
exports.getMe = async (req, res, next) => {
try {
const user = await User.findById(req.user.id).select('-password');
res.json(user);
} catch (err) {
next(err);
}
};
Loading…
Cancel
Save