userController.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. const User = require('../models/User');
  2. const jwt = require('jsonwebtoken');
  3. // 生成 JWT token
  4. const generateToken = (id) => {
  5. return jwt.sign({ id }, process.env.JWT_SECRET || 'your-secret-key', {
  6. expiresIn: '30d'
  7. });
  8. };
  9. // @desc 用户登录
  10. // @route POST /api/users/login
  11. // @access Public
  12. const loginUser = async (req, res) => {
  13. try {
  14. console.log('收到登录请求:', req.body);
  15. const { username, password } = req.body;
  16. if (!username || !password) {
  17. console.log('缺少用户名或密码');
  18. return res.status(400).json({ message: '请提供用户名和密码' });
  19. }
  20. const user = await User.findByUsername(username);
  21. console.log('查询到的用户:', user ? '找到用户' : '未找到用户');
  22. if (!user) {
  23. console.log('用户不存在');
  24. return res.status(401).json({ message: '用户名或密码错误' });
  25. }
  26. const isMatch = await User.comparePassword(password, user.password);
  27. console.log('密码匹配结果:', isMatch);
  28. if (isMatch) {
  29. console.log('登录成功,生成token');
  30. const token = generateToken(user.id);
  31. // console.log('生成的token:', token);
  32. res.json({
  33. _id: user.id,
  34. username: user.username,
  35. role: user.role,
  36. token: token
  37. });
  38. } else {
  39. console.log('密码错误');
  40. res.status(401).json({ message: '用户名或密码错误' });
  41. }
  42. } catch (error) {
  43. console.error('登录错误:', error);
  44. res.status(500).json({
  45. message: '服务器错误',
  46. error: process.env.NODE_ENV === 'development' ? error.message : undefined
  47. });
  48. }
  49. };
  50. // @desc 修改密码
  51. // @route PUT /api/users/password
  52. // @access Private
  53. const updatePassword = async (req, res) => {
  54. try {
  55. const { currentPassword, newPassword } = req.body;
  56. const user = await User.findById(req.user.id);
  57. if (await User.comparePassword(currentPassword, user.password)) {
  58. await User.updatePassword(user.id, newPassword);
  59. res.json({ message: '密码修改成功' });
  60. } else {
  61. res.status(401).json({ message: '当前密码错误' });
  62. }
  63. } catch (error) {
  64. res.status(500).json({ message: '服务器错误' });
  65. }
  66. };
  67. // @desc 获取用户信息
  68. // @route GET /api/users/profile
  69. // @access Private
  70. const getUserProfile = async (req, res) => {
  71. try {
  72. const user = await User.findById(req.user.id);
  73. if (user) {
  74. res.json({
  75. _id: user.id,
  76. username: user.username,
  77. role: user.role
  78. });
  79. } else {
  80. res.status(404).json({ message: '用户不存在' });
  81. }
  82. } catch (error) {
  83. res.status(500).json({ message: '服务器错误' });
  84. }
  85. };
  86. // @desc 获取用户信息
  87. // @route GET /api/users/:id
  88. // @access Private
  89. const getUserById = async (req, res) => {
  90. try {
  91. const user = await User.findById(req.params.id);
  92. if (user) {
  93. res.json({
  94. id: user.id,
  95. username: user.username,
  96. contact: user.contact || '',
  97. remark: user.remark || '',
  98. role: user.role
  99. });
  100. } else {
  101. res.status(404).json({ message: '用户不存在' });
  102. }
  103. } catch (error) {
  104. console.error('获取用户信息失败:', error);
  105. res.status(500).json({ message: '服务器错误' });
  106. }
  107. };
  108. // @desc 更新用户信息
  109. // @route PUT /api/users/:id
  110. // @access Private
  111. const updateUser = async (req, res) => {
  112. try {
  113. const { contact, remark } = req.body;
  114. const userId = req.params.id;
  115. // 检查用户是否存在
  116. const user = await User.findById(userId);
  117. if (!user) {
  118. return res.status(404).json({ message: '用户不存在' });
  119. }
  120. // 更新用户信息
  121. await User.update(userId, {
  122. contact,
  123. remark
  124. });
  125. res.json({
  126. success: true,
  127. message: '用户信息更新成功'
  128. });
  129. } catch (error) {
  130. console.error('更新用户信息失败:', error);
  131. res.status(500).json({
  132. success: false,
  133. message: '服务器错误'
  134. });
  135. }
  136. };
  137. module.exports = {
  138. loginUser,
  139. updatePassword,
  140. getUserProfile,
  141. getUserById,
  142. updateUser
  143. };