'use strict'; const Service = require('egg').Service; class UserService extends Service { constructor(ctx) { super(ctx); } /** * 用户登录(重构版) * @param {string} username - 用户名/手机号/邮箱 * @param {string} password - 密码 * @param {string} loginType - 登录类型: username, phone, email, auto * @param {string} platformCode - 平台编码(web、pda、mini等) * @return {Object} 登录结果 */ async login(username, password, loginType = 'auto') { const { ctx, app } = this; try { // 统一的认证错误信息 const authError = new Error('用户名或密码错误或账号状态异常'); authError.code = 'AUTH_FAILED'; // 1. 查找用户 const user = await this.findUserByIdentifier(username, loginType); if (!user) { app.coreLogger.warn(`登录失败: 用户不存在 [${username}]`); throw authError; } console.log('登录获取用户信息', user); // 2. 检查用户状态 try { this.checkUserStatus(user); } catch (statusError) { app.coreLogger.warn(`登录失败: 用户状态异常 [${user.id}] - ${statusError.message}`); throw authError; } // 3. 验证密码 const isPasswordValid = await user.verifyPassword(password); if (!isPasswordValid) { app.coreLogger.warn(`登录失败: 密码错误 [${user.id}]`); throw authError; } // 4. 更新最后登录时间 await this.updateLastLoginTime(user.id); // 5. 设置设备类型(用于菜单查询) const platformCode = ctx.header.platform || 'web'; // 6. 获取用户完整信息 const userInfo = await this.findById(user.id); console.log('用户信息', userInfo); // 7. 如果用户有角色但当前平台没有激活角色,则自动设置一个 if (userInfo.roles && userInfo.roles.length > 0 && !userInfo.role_id) { await this.ensurePlatformActiveRole(user.id, userInfo.roles[0].id, platformCode); } // 8. 生成 JWT Token const tokenPayload = { id: user.id, username: user.username, real_name: user.real_name, platform_code: platformCode, current_role_id: userInfo.employees_id, current_store_id: userInfo.store_id || null, }; const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, { expiresIn: app.config.jwt.expiresIn, }); return { success: true, data: { user: { id: user.id, username: user.username, real_name: user.real_name, phone: user.phone, email: user.email, status: user.status, last_login_at: user.last_login_at, roles: userInfo.roles, role_id: userInfo.role_id, menus: userInfo.menus, permissions: userInfo.permissions, userRole: userInfo.userRole, realName: userInfo.realName, }, token, }, code: 200, message: '登录成功', }; } catch (error) { app.coreLogger.error(`登录异常: ${error.message}`); return { success: false, data: null, code: 0, message: '用户名或密码错误或账号状态异常', }; } } /** * 切换角色(重构版) * @param {Object} data - 切换角色数据 * @param {number} data.roleId - 角色关联ID (account_store_role.id) * @param {string} data.platformCode - 平台编码(web、pda、mini等) * @return {Object} 切换结果 */ async changeRole(data) { const { ctx, app } = this; const user = ctx.state.user || ctx.user; try { // 验证角色关联是否存在且有效 const accountStoreRole = await ctx.model.AccountStoreEmployee.findOne({ where: { id: data.roleId, account_id: user.id, status: 1, }, include: [ { model: ctx.model.EmployeeRole, as: 'employeeRole', }, ], }); if (!accountStoreRole) { throw new Error('角色不存在或未授权'); } const platformCode = ctx.header.platform || 'web'; // 更新平台激活角色 await ctx.model.AccountPlatformActive.upsert({ account_id: user.id, employee_id: data.roleId, platform_code: platformCode, }); // 清理缓存 await this.clearUserCache(user.id); // 获取更新后的用户信息 const userInfo = await this.findById(user.id); const tokenPayload = { id: user.id, username: user.username, real_name: user.real_name, platform_code: platformCode, current_role_id: userInfo.employees_id, current_store_id: accountStoreRole.store_id || null, }; const newToken = app.jwt.sign(tokenPayload, app.config.jwt.secret, { expiresIn: app.config.jwt.expiresIn, }); return { success: true, data: { user: userInfo, token: newToken, }, code: 200, message: '角色切换成功', }; } catch (error) { app.coreLogger.error(`切换角色失败: ${error.message}`); return { success: false, data: null, code: 0, message: error.message || '角色切换失败', }; } } /** * 获取用户信息(重构版) * @param {Object} data - 请求数据 * @return {Object} 用户信息 */ async info(data) { const { ctx } = this; try { const userId = ctx.userId || (ctx.user && ctx.user.id); const user = await this.findById(userId); return { success: true, data: user, code: 200, }; } catch (error) { console.log(error); return { success: false, data: null, code: 0, }; } } /** * 查找用户所有的角色以及对应的主体(重构版) * @param {number} userId - 用户ID * @param {string} platformCode - 平台编码 * @return {Promise} */ async getRoles(userId) { const { ctx } = this; const platformCode = ctx.header.platform || 'web'; const project = ctx.header.project; try { // 获取用户的所有角色关联 const store_where = { status: 1, }; if (project != 'all') { store_where.project = project; } console.log('store_where', store_where, project, platformCode, ctx.header); const accountStoreEmployees = await ctx.model.AccountStoreEmployee.findAll({ where: { account_id: userId, status: 1, }, include: [ { model: ctx.model.EmployeeRole, as: 'employeeRole', attributes: [ 'id', 'role_id' ], }, { model: ctx.model.Store, as: 'store', attributes: [ 'id', 'company_name', 'project', 'auth_end' ], where: store_where, }, ], order: [[ 'created_at', 'DESC' ]], }); if (!accountStoreEmployees) { throw ('没有符合的角色'); } console.log('accountStoreEmployees>>>>>', accountStoreEmployees); // 获取当前平台的激活角色 let activeEmployeeId = null; let employee_id = null; let realName = null; let userRole = ''; const platformActive = await ctx.model.AccountPlatformActive.findOne({ where: { account_id: userId, platform_code: platformCode, }, attributes: [ 'account_id', 'employee_id', 'platform_code' ], }); if (platformActive) { employee_id = platformActive.employee_id; } // 转换数据格式 const Employees = accountStoreEmployees.map(item => ({ id: item.id, store_id: item.store_id, store_name: item.store.company_name, is_primary: platformActive && platformActive.employee_id === item.id ? 1 : 0, real_name: item.real_name, auth_end: item.store.auth_end, role_type: item.store.project, })); // 确定当前激活角色 for (const Employee of Employees) { if (Employee.is_primary == 1) { activeEmployeeId = Employee.id; realName = Employee.real_name; userRole = Employee.role_type == 1 ? 'warehouse' : 'customer'; break; } } // 如果没有激活角色,选择第一个 if (!activeEmployeeId && Employees.length > 0) { activeEmployeeId = Employees[0].id; realName = Employees[0].real_name; userRole = Employees[0].role_type == 1 ? 'warehouse' : 'customer'; // 设置为激活角色 if (Employees[0].id) { await this.ensurePlatformActiveRole(userId, Employees[0].id, platformCode); } } // 获取菜单和权限 const menus = await this.getMenus(activeEmployeeId); console.log('获取菜单', activeEmployeeId, menus); const permissions = await this.getPermissions(activeEmployeeId); return { Employees, activeEmployeeId, menus, permissions, userRole, realName }; } catch (error) { console.error('获取用户角色失败:', error); return [[], null, [], [], '', null ]; } } /** * 根据ID查找用户(重构版) * @param {number} userId - 用户ID * @param {string} platformCode - 平台编码 * @param useCache * @return {Promise} */ async findById(userId, useCache = true) { const { ctx } = this; const platformCode = ctx.header.platform || 'web'; const project = ctx.header.project; console.log(`调用${ctx.query_count}次,平台为${platformCode}`); ctx.query_count++; try { // 生成缓存key const cacheKey = `user:info:${userId}:${platformCode}`; // 1. 尝试从缓存获取 if (useCache) { try { const cachedUser = await this.app.getCacheAsync(cacheKey); if (cachedUser) { console.log('用户信息缓存命中:', userId); return cachedUser; } } catch (cacheError) { console.warn('获取用户缓存失败:', cacheError.message); // 缓存失败不影响主流程,继续查询数据库 } } // 2. 从数据库获取用户基本信息 const user = await this.ctx.model.Account.findOne({ where: { id: userId }, attributes: [ 'id', 'real_name', 'email', 'status', 'username', 'phone', 'last_login_at', 'last_login_ip' ], }); if (!user) { // 如果用户不存在,也缓存null值避免频繁查询 if (useCache) { await this.setUserCache(cacheKey, null, 300); // 缓存5分钟 } return null; } // 3. 获取角色信息(这个方法内部也有缓存逻辑) const { Employees, activeEmployeeId, menus, permissions, userRole, realName } = await this.getRoles(userId); console.log('activeEmployeeId>>>>>>>>', activeEmployeeId); // 4. 获取当前角色对应的仓库ID let storeId = null; let storeName = null; let storeCode = null; let roleName = null; let auth_end = null; let employees_name = null; if (activeEmployeeId && Employees.length > 0) { const currentRole = Employees.find(Employee => Employee.id === activeEmployeeId); if (currentRole) { storeId = currentRole.store_id; storeName = currentRole.store_name; storeCode = currentRole.store_code; roleName = currentRole.role_name; employees_name = currentRole.real_name; auth_end = currentRole.auth_end; } } const avatar = await this.getAvatarByEmployeeId(activeEmployeeId); if (platformCode == 'pda' && !activeEmployeeId) { throw ('无登录权限'); } // 5. 组合用户信息 const userInfo = { id: user.id, status: user.status, employees: Employees, auth_end, employees_id: activeEmployeeId, employees_name: employees_name || '未命名', loginIp: user.last_login_ip, role_name: roleName, store_id: storeId, store_name: storeName, store_code: storeCode, menus, permissions, userRole, platform_code: platformCode, avatar, cached_at: new Date().toISOString(), }; // 6. 设置缓存 if (useCache) { console.log('设置用户缓存', userInfo); await this.setUserCache(cacheKey, userInfo, 300); // 缓存5分钟 } console.log('用户信息数据库查询:', userId); return userInfo; } catch (error) { console.error('根据ID查找用户失败:', error); return null; } } /** * 设置用户缓存 * @param cacheKey * @param userInfo * @param ttl * @private */ async setUserCache(cacheKey, userInfo, ttl = 300) { try { // 移除缓存标识字段 if (userInfo) { const { cached_at, ...cacheData } = userInfo; await this.app.setCacheAsync(cacheKey, cacheData, ttl); } else { await this.app.setCacheAsync(cacheKey, null, ttl); } } catch (error) { console.warn('设置用户缓存失败:', error.message); } } async getAvatarByEmployeeId(employeeId) { const { ctx, app } = this; const { Op } = app.Sequelize; let url = ''; const image = await ctx.model.FileReference.findOne({ where: { business_type: 'avater', business_id: employeeId, }, include: [{ model: ctx.model.File, as: 'file', attributes: [ 'file_url' ], required: true, }], }); if (image) { url = image.file.file_url; } return url; } /** * 清除用户缓存 * @param userId * @param platformCode */ async clearUserCache(userId, platformCode = null) { try { if (platformCode) { // 清除指定平台的缓存 const cacheKey = `user:info:${userId}:${platformCode}`; await this.app.setCacheAsync(cacheKey, null, 1); } else { // 清除用户所有平台的缓存 const platforms = [ 'web', 'pda', 'mini', 'app' ]; for (const platform of platforms) { const cacheKey = `user:info:${userId}:${platform}`; await this.app.setCacheAsync(cacheKey, null, 1); } } // 同时清除相关的缓存 await this.clearRelatedCache(userId); console.log('用户缓存已清除:', userId); return true; } catch (error) { console.warn('清除用户缓存失败:', error.message); return false; } } /** * 清除用户相关缓存 * @param userId * @private */ async clearRelatedCache(userId) { try { // 清除用户基本信息缓存 const basicCacheKeys = [ `user:basic:${userId}`, `account:username:${userId}`, `account:phone:${userId}`, `account:email:${userId}`, ]; for (const key of basicCacheKeys) { await this.app.setCacheAsync(key, null, 1); } // 清除用户角色缓存 const roleCacheKey = `user:roles:${userId}`; await this.app.setCacheAsync(roleCacheKey, null, 1); // 清除用户权限缓存 const permCacheKeys = [ `user:permissions:${userId}`, `user:menus:${userId}`, ]; for (const key of permCacheKeys) { await this.app.setCacheAsync(key, null, 1); } } catch (error) { console.warn('清除相关缓存失败:', error.message); } } /** * 获取权限列表(重构版) * @param {number} roleId - 角色ID * @param activeEmployeeId * @return {Promise} */ async getPermissions(activeEmployeeId) { const { ctx, app } = this; const { Sequelize } = app; const { Op } = Sequelize; if (!activeEmployeeId) { return []; } try { // 1. 获取员工的角色 const roles = await ctx.model.EmployeeRole.findAll({ where: { employee_id: activeEmployeeId, }, raw: true, // 获取纯数据对象 }); console.log('员工绑定的角色', roles); if (!roles || roles.length === 0) { return []; } const roleIds = roles.map(item => item.role_id); // 2. 获取角色的权限 const rolePermissions = await ctx.model.RolePermission.findAll({ where: { role_id: { [Op.in]: roleIds, }, }, raw: true, }); if (!rolePermissions || rolePermissions.length === 0) { return []; } const permissionIds = rolePermissions.map(item => item.permission_id); const permissions = await ctx.model.Permission.findAll({ where: { id: { [Op.in]: permissionIds, }, // 修正 like 查询 type: { [ctx.app.Sequelize.Op.notLike]: '%_pages', }, }, attributes: [ 'id', 'path', 'type' ], order: [ [ 'sort', 'ASC' ], ], }); console.log('permissions列表', permissions); if (!permissions) { return []; } return permissions.map(item => item.path); } catch (error) { console.error('获取权限列表失败:', error); return []; } } async getMenus(activeEmployeeId) { const { ctx, app } = this; const { Sequelize } = app; const { Op } = Sequelize; console.log('获取员工菜单员工id:', activeEmployeeId); if (!ctx.header.platform || !activeEmployeeId) { return []; } try { // 1. 获取员工的角色 const roles = await ctx.model.EmployeeRole.findAll({ where: { employee_id: activeEmployeeId, }, raw: true, // 获取纯数据对象 }); console.log('员工绑定的角色', roles); if (!roles || roles.length === 0) { return []; } const roleIds = roles.map(item => item.role_id); // 2. 获取角色的权限 const rolePermissions = await ctx.model.RolePermission.findAll({ where: { role_id: { [Op.in]: roleIds, }, }, raw: true, }); if (!rolePermissions || rolePermissions.length === 0) { return []; } const permissionIds = rolePermissions.map(item => item.permission_id); // 3. 获取权限对应的菜单(根据设备筛选) const permissions = await ctx.model.Permission.findAll({ where: { id: { [Op.in]: permissionIds, }, // 修正 like 查询 type: { [Op.like]: `${ctx.header.platform}_%`, }, }, order: [ [ 'sort', 'ASC' ], ], }); if (!permissions || permissions.length === 0) { return []; } return this.convertToRoutes(permissions); } catch (error) { ctx.logger.error('获取菜单列表失败:', error); return []; } } /** * 转换权限为路由格式(保持不变) * @param data */ async convertToRoutes(data) { const map = new Map(); const roots = []; // 创建所有节点的映射 data.forEach(item => { map.set(item.id, { id: item.id, path: item.path, component: item.component, name: item.name, redirect: item.redirect, meta: { title: item.meta_title, icon: item.meta_icon, }, hidden: item.hidden === 1, alwaysShow: item.always_show === 1, sort: item.sort, children: [], }); }); // 构建树形结构 data.forEach(item => { const node = map.get(item.id); if (item.parent_id === 0) { roots.push(node); } else { const parent = map.get(item.parent_id); if (parent) { parent.children.push(node); } } }); // 递归排序函数 const sortTree = nodes => { if (!nodes || nodes.length === 0) return; nodes.sort((a, b) => { return a.sort - b.sort || a.id - b.id; }); nodes.forEach(node => { if (node.children && node.children.length > 0) { sortTree(node.children); } }); }; // 从根节点开始排序 sortTree(roots); // 移除辅助字段 const cleanNode = node => { const { id, sort, ...rest } = node; if (rest.children && rest.children.length > 0) { rest.children = rest.children.map(child => cleanNode(child)); } return rest; }; return roots.map(root => cleanNode(root)); } /** * 根据标识符查找用户(已重构) * @param identifier * @param type * @param useCache */ async findUserByIdentifier(identifier, type = 'auto', useCache = true) { const { ctx, app } = this; let user; if (type === 'auto') { // 自动判断类型 const Op = app.Sequelize.Op; if (/^1[3-9]\d{9}$/.test(identifier)) { // 手机号格式 user = await ctx.model.Account.findOne({ where: { phone: identifier }, }); } else if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(identifier)) { // 邮箱格式 user = await ctx.model.Account.findOne({ where: { email: identifier }, }); } else { // 默认按用户名 user = await ctx.model.Account.findOne({ where: { username: identifier }, }); } } else { // 指定类型 let whereCondition = {}; switch (type) { case 'phone': whereCondition = { phone: identifier }; break; case 'email': whereCondition = { email: identifier }; break; case 'username': default: whereCondition = { username: identifier }; break; } user = await ctx.model.Account.findOne({ where: whereCondition, }); } if (user) { // 设置标志,表示不隐藏敏感字段 user._hideSensitive = false; } return user; } /** * 检查用户状态(保持不变) * @param user */ checkUserStatus(user) { if (user.status === 0) { throw new Error('账号已被禁用,请联系管理员'); } if (user.status === 2) { throw new Error('账号已离职,无法登录'); } if (user.status !== 1) { throw new Error('账号状态异常'); } } /** * 验证密码(重构版) * @param inputPassword * @param storedHash * @param salt */ async verifyPassword(inputPassword, storedHash, salt) { const crypto = require('crypto'); const hash = crypto.createHash('sha256'); hash.update(inputPassword + salt); const encryptedPassword = hash.digest('hex'); if (encryptedPassword !== storedHash) { throw new Error('密码错误'); } return true; } /** * 加密密码(保持不变) * @param password * @param salt */ async encryptPassword(password, salt) { const crypto = require('crypto'); const hash = crypto.createHash('sha256'); hash.update(password + salt); return hash.digest('hex'); } /** * 生成密码盐(保持不变) */ generateSalt() { const crypto = require('crypto'); return crypto.randomBytes(10).toString('hex'); } /** * 更新最后登录时间(重构版) * @param userId */ async updateLastLoginTime(userId) { const { ctx } = this; console.log('登录上下文', ctx.request.header['x-real-ip']); await ctx.model.Account.update({ last_login_at: new Date(), last_login_ip: ctx.request.header['x-real-ip'], }, { where: { id: userId }, }); await this.clearUserCache(userId); } /** * 确保平台激活角色存在 * @param accountId * @param accountStoreRoleId * @param platformCode * @private */ async ensurePlatformActiveRole(accountId, accountStoreRoleId, platformCode) { const { ctx } = this; try { await ctx.model.AccountPlatformActive.upsert({ account_id: accountId, employee_id: accountStoreRoleId, platform_code: platformCode, }); } catch (error) { console.warn('设置平台激活角色失败:', error.message); } } /** * 用户注册(重构版) * @param userInfo */ async register(userInfo) { const { ctx, app } = this; // 检查用户名是否已存在 const existingUser = await this.findUserByIdentifier(userInfo.username, 'username'); if (existingUser) { throw new Error('用户名已存在'); } // 生成密码盐 const salt = this.generateSalt(); // 加密密码 const passwordHash = await this.encryptPassword(userInfo.password, salt); // 创建用户 const user = await ctx.model.Account.create({ username: userInfo.username, email: userInfo.email || '', password_hash: passwordHash, real_name: userInfo.real_name || '', status: 1, salt, }); return { userId: user.id, username: user.username, code: 200, message: '注册成功', }; } } module.exports = UserService;