const bcrypt = require('bcryptjs'); const { Op } = require('sequelize'); const User = require('../models/User'); const Role = require('../models/Role'); const { logOperation } = require('../utils/logger'); // 获取用户列表 exports.getUserList = async (req, res) => { try { const { page = 1, pageSize = 10, username, roleId, status } = req.query; // 构建查询条件 const where = { isDeleted: 0, isSuperAdmin: 0 }; if (username) { where.username = { [Op.like]: `%${username}%` }; } if (roleId) { where.roleId = roleId; } if (status) { where.status = status; } // 查询用户列表 const { count, rows } = await User.findAndCountAll({ where, attributes: ['id', 'username', 'nickname', 'roleId', 'status', 'createdAt', 'updatedAt'], include: [{ model: Role, as: 'role', attributes: ['id', 'name', 'code'] }], order: [['createdAt', 'DESC']], offset: (page - 1) * pageSize, limit: parseInt(pageSize) }); res.json({ code: 200, message: '获取成功', data: { list: rows, total: count, page: parseInt(page), pageSize: parseInt(pageSize) } }); } catch (error) { console.error('获取用户列表错误:', error); res.status(500).json({ code: 500, message: '获取用户列表失败', error: error.message }); } }; // 获取用户详情 exports.getUserById = async (req, res) => { try { const { id } = req.params; const user = await User.findByPk(id, { where: { isDeleted: 0 }, attributes: ['id', 'username', 'nickname', 'roleId', 'status', 'createdAt', 'updatedAt'], include: [{ model: Role, as: 'role', attributes: ['id', 'name', 'code'] }] }); if (!user) { return res.status(404).json({ code: 404, message: '用户不存在' }); } res.json({ code: 200, message: '获取成功', data: user }); // 记录操作日志 await logOperation({ userId: req.user.id, username: req.user.username, module: '用户管理', action: '查询', description: `获取用户详情,ID: ${id}`, method: req.method, path: req.path, ip: req.ip, status: 'success' }); } catch (error) { console.error('获取用户详情错误:', error); res.status(500).json({ code: 500, message: '获取用户详情失败', error: error.message }); } }; // 创建用户 exports.createUser = async (req, res) => { try { const { username, password, nickname, roleId } = req.body; // 参数验证 if (!username || !password) { return res.status(400).json({ code: 400, message: '用户名和密码不能为空' }); } if (username.length < 3 || username.length > 20) { return res.status(400).json({ code: 400, message: '用户名长度应在3-20个字符之间' }); } if (password.length < 6 || password.length > 20) { return res.status(400).json({ code: 400, message: '密码长度应在6-20个字符之间' }); } if (!roleId) { return res.status(400).json({ code: 400, message: '角色不能为空' }); } // 检查角色是否存在 const role = await Role.findByPk(roleId, { where: { isDeleted: 0, status: 'active' } }); if (!role) { return res.status(400).json({ code: 400, message: '角色不存在或已禁用' }); } // 检查用户名是否已存在 const existingUser = await User.findOne({ where: { username, isDeleted: 0 } }); if (existingUser) { return res.status(400).json({ code: 400, message: '用户名已存在' }); } // 加密密码 const hashedPassword = await bcrypt.hash(password, 10); // 创建用户 const user = await User.create({ username, password: hashedPassword, nickname: nickname || null, roleId, createBy: req.user.id, updateBy: req.user.id }); res.json({ code: 200, message: '创建成功', data: { id: user.id, username: user.username, nickname: user.nickname, roleId: user.roleId, createdAt: user.createdAt } }); // 记录操作日志 await logOperation({ userId: req.user.id, username: req.user.username, module: '用户管理', action: '创建', description: `创建用户: ${username}`, method: req.method, path: req.path, ip: req.ip, status: 'success' }); } catch (error) { console.error('创建用户错误:', error); res.status(500).json({ code: 500, message: '创建用户失败', error: error.message }); } }; // 更新用户 exports.updateUser = async (req, res) => { try { const { id } = req.params; const { nickname, roleId, status } = req.body; // 查找用户 const user = await User.findByPk(id, { where: { isDeleted: 0 } }); if (!user) { return res.status(404).json({ code: 404, message: '用户不存在' }); } // 检查角色是否存在 if (roleId) { const role = await Role.findByPk(roleId, { where: { isDeleted: 0, status: 'active' } }); if (!role) { return res.status(400).json({ code: 400, message: '角色不存在或已禁用' }); } } // 构建更新数据 const updateData = { updateBy: req.user.id }; if (nickname !== undefined) updateData.nickname = nickname || null; if (roleId !== undefined) updateData.roleId = roleId; if (status !== undefined) updateData.status = status; // 更新用户 await user.update(updateData); res.json({ code: 200, message: '更新成功', data: { id: user.id, username: user.username, nickname: user.nickname, roleId: user.roleId, status: user.status, updatedAt: user.updatedAt } }); // 记录操作日志 await logOperation({ userId: req.user.id, username: req.user.username, module: '用户管理', action: '更新', description: `更新用户: ${user.username}`, method: req.method, path: req.path, ip: req.ip, status: 'success' }); } catch (error) { console.error('更新用户错误:', error); res.status(500).json({ code: 500, message: '更新用户失败', error: error.message }); } }; // 删除用户 exports.deleteUser = async (req, res) => { try { const { id } = req.params; // 不能删除自己 if (parseInt(id) === req.user.id) { return res.status(400).json({ code: 400, message: '不能删除自己的账号' }); } // 查找用户 const user = await User.findByPk(id, { where: { isDeleted: 0 } }); if (!user) { return res.status(404).json({ code: 404, message: '用户不存在' }); } // 软删除 await user.update({ isDeleted: 1, updateBy: req.user.id }); res.json({ code: 200, message: '删除成功' }); // 记录操作日志 await logOperation({ userId: req.user.id, username: req.user.username, module: '用户管理', action: '删除', description: `删除用户: ${user.username}`, method: req.method, path: req.path, ip: req.ip, status: 'success' }); } catch (error) { console.error('删除用户错误:', error); res.status(500).json({ code: 500, message: '删除用户失败', error: error.message }); } }; // 重置用户密码 exports.resetUserPassword = async (req, res) => { try { const { id } = req.params; const defaultPassword = '123456'; // 查找用户 const user = await User.findByPk(id, { where: { isDeleted: 0 } }); if (!user) { return res.status(404).json({ code: 404, message: '用户不存在' }); } // 加密默认密码 const hashedPassword = await bcrypt.hash(defaultPassword, 10); // 更新密码 await user.update({ password: hashedPassword, updateBy: req.user.id }); res.json({ code: 200, message: '密码重置成功', data: { defaultPassword } }); // 记录操作日志 await logOperation({ userId: req.user.id, username: req.user.username, module: '用户管理', action: '重置密码', description: `重置用户密码: ${user.username}`, method: req.method, path: req.path, ip: req.ip, status: 'success' }); } catch (error) { console.error('重置密码错误:', error); res.status(500).json({ code: 500, message: '重置密码失败', error: error.message }); } }; // 获取用户列表(用于下拉选择) exports.getAllUsers = async (req, res) => { try { const users = await User.findAll({ where: { isDeleted: 0, status: 'active' }, attributes: ['id', 'username', 'nickname'] }); res.json({ code: 200, message: '获取用户列表成功', data: users }); } catch (error) { console.error('获取用户列表错误:', error); res.status(500).json({ code: 500, message: '获取用户列表失败', error: error.message }); } }; // 获取当前用户信息 exports.getCurrentUserInfo = async (req, res) => { try { const user = await User.findByPk(req.user.id, { attributes: ['id', 'username', 'nickname', 'status', 'createdAt', 'updatedAt'], include: [{ model: Role, as: 'role', attributes: ['id', 'name', 'code'] }] }); if (!user) { return res.status(404).json({ code: 404, message: '用户不存在' }); } res.json({ code: 200, message: '获取用户信息成功', data: user }); } catch (error) { console.error('获取用户信息失败:', error); res.status(500).json({ code: 500, message: '获取用户信息失败', error: error.message }); } }; // 更新个人资料 exports.updateUserProfile = async (req, res) => { try { const { nickname } = req.body; // 验证昵称 if (!nickname || nickname.trim().length === 0) { return res.status(400).json({ code: 400, message: '昵称不能为空' }); } // 更新用户信息 const user = await User.findByPk(req.user.id); if (!user) { return res.status(404).json({ code: 404, message: '用户不存在' }); } await user.update({ nickname, updateBy: req.user.id }); // 记录操作日志 await logOperation({ userId: req.user.id, username: req.user.username, module: '个人中心', action: '更新资料', description: '更新个人资料', method: req.method, path: req.path, ip: req.ip, status: 'success' }); res.json({ code: 200, message: '个人资料更新成功', data: { id: user.id, username: user.username, nickname: user.nickname, status: user.status, createdAt: user.createdAt, updatedAt: user.updatedAt } }); } catch (error) { console.error('更新个人资料失败:', error); res.status(500).json({ code: 500, message: '更新个人资料失败', error: error.message }); } }; // 修改密码 exports.changePassword = async (req, res) => { try { const { oldPassword, newPassword } = req.body; // 验证参数 if (!oldPassword || !newPassword) { return res.status(400).json({ code: 400, message: '旧密码和新密码不能为空' }); } if (newPassword.length < 6) { return res.status(400).json({ code: 400, message: '新密码长度至少6位' }); } // 验证旧密码 const user = await User.findByPk(req.user.id); if (!user) { return res.status(404).json({ code: 404, message: '用户不存在' }); } const isPasswordValid = await bcrypt.compare(oldPassword, user.password); if (!isPasswordValid) { return res.status(400).json({ code: 400, message: '旧密码错误' }); } // 更新密码 const hashedPassword = await bcrypt.hash(newPassword, 10); await user.update({ password: hashedPassword, updateBy: req.user.id }); // 记录操作日志 await logOperation({ userId: req.user.id, username: req.user.username, module: '个人中心', action: '修改密码', description: '修改个人密码', method: req.method, path: req.path, ip: req.ip, status: 'success' }); res.json({ code: 200, message: '密码修改成功' }); } catch (error) { console.error('修改密码失败:', error); res.status(500).json({ code: 500, message: '修改密码失败', error: error.message }); } };