123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- import bcrypt from 'bcryptjs';
- import jwt from 'jsonwebtoken';
- import pool from '../config/db.js';
- // 生成JWT令牌
- const generateToken = (id) => {
- return jwt.sign({ id }, process.env.JWT_SECRET, {
- expiresIn: '30d',
- });
- };
- // @desc 注册新用户
- // @route POST /api/users
- // @access Public
- const registerUser = async (req, res) => {
- const { email, password } = req.body;
- try {
- // 检查用户是否已存在
- const [existingUsers] = await pool.query('SELECT * FROM users WHERE email = ?', [email]);
- if (existingUsers.length > 0) {
- return res.status(400).json({ message: '用户已存在' });
- }
- // 加密密码
- const salt = await bcrypt.genSalt(10);
- const hashedPassword = await bcrypt.hash(password, salt);
- // 创建用户
- const [result] = await pool.query('INSERT INTO users (email, password) VALUES (?, ?)', [
- email,
- hashedPassword,
- ]);
- if (result.insertId) {
- res.status(201).json({
- id: result.insertId,
- email,
- token: generateToken(result.insertId),
- });
- } else {
- res.status(400).json({ message: '无效的用户数据' });
- }
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: '服务器错误' });
- }
- };
- // @desc 认证用户 & 获取令牌
- // @route POST /api/users/login
- // @access Public
- const loginUser = async (req, res) => {
- const { email, password } = req.body;
- try {
- // 检查用户是否存在
- const [users] = await pool.query('SELECT * FROM users WHERE email = ?', [email]);
- if (users.length === 0) {
- return res.status(401).json({ message: '邮箱或密码不正确' });
- }
- const user = users[0];
- // 验证密码
- const isMatch = await bcrypt.compare(password, user.password);
- if (!isMatch) {
- return res.status(401).json({ message: '邮箱或密码不正确' });
- }
- res.json({
- id: user.id,
- email: user.email,
- token: generateToken(user.id),
- });
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: '服务器错误' });
- }
- };
- // @desc 获取用户资料
- // @route GET /api/users/profile
- // @access Private
- const getUserProfile = async (req, res) => {
- try {
- res.json({
- id: req.user.id,
- email: req.user.email,
- });
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: '服务器错误' });
- }
- };
- export { registerUser, loginUser, getUserProfile };
|