From 6e033c053abffdb047480cf36490bf7b2c9283d9 Mon Sep 17 00:00:00 2001 From: phgkfux43 <3469266505@qq.com> Date: Sat, 26 Apr 2025 22:38:01 +0800 Subject: [PATCH] ADD file via upload --- auth.js | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 auth.js diff --git a/auth.js b/auth.js new file mode 100644 index 0000000..fb0c64b --- /dev/null +++ b/auth.js @@ -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); + } +}; \ No newline at end of file