'use strict'; const Service = require('egg').Service; const crypto = require('node:crypto'); const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:'; const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:'; const WECHAT_BIND_SCAN_CACHE_PREFIX = 'user:wechat:bind:scan:'; const WECHAT_BIND_CACHE_TTL_SECONDS = 60; const WECHAT_BIND_SCAN_CACHE_TTL_SECONDS = 180; const WECHAT_BIND_EVENT_CHANNEL_PREFIX = 'user:wechat:bind:event:'; const WECHAT_BIND_LONG_POLL_TIMEOUT_MS = 60000; const WECHAT_LOGIN_CLIENT_CACHE_PREFIX = 'user:wechat:login:client:'; const WECHAT_LOGIN_CODE_CACHE_PREFIX = 'user:wechat:login:code:'; const WECHAT_LOGIN_EVENT_CHANNEL_PREFIX = 'user:wechat:login:event:'; const WECHAT_LOGIN_CACHE_TTL_SECONDS = 60; class UserService extends Service { /** * 根据平台解析菜单权限类型过滤条件 * @param {string} platform 平台标识 * @return {{ type: object }} 菜单权限类型过滤条件 */ getMenuTypeWhereByPlatform(platform) { const { Op } = this.app.Sequelize; const normalizedPlatform = String(platform || '').trim().toLowerCase(); const platformTypeStrategy = { web: { mode: 'prefix', values: [ 'web_' ], }, pda: { mode: 'prefix', values: [ 'pda_' ], }, miniprogram: { mode: 'prefix', values: [ 'miniprogram_' ], }, workerstation: { mode: 'type', values: [ 'workerstation_pages' ], }, workstation: { mode: 'type', values: [ 'workerstation_pages' ], }, }; const strategy = platformTypeStrategy[normalizedPlatform]; if (!strategy) { return { type: { [Op.like]: `${normalizedPlatform}_%`, }, }; } if (strategy.mode === 'prefix') { const likeConditions = strategy.values.map(prefix => ({ [Op.like]: `${prefix}%` })); if (likeConditions.length === 1) { return { type: likeConditions[0], }; } return { type: { [Op.or]: likeConditions, }, }; } return { type: strategy.values.length === 1 ? strategy.values[0] : { [Op.in]: strategy.values, }, }; } getCurrentAccountId() { const { ctx } = this; const rawUserId = ctx.userId || (ctx.user && ctx.user.id); const accountId = Number(rawUserId); if (!Number.isFinite(accountId) || accountId <= 0) { return null; } return accountId; } getWechatBindCacheKey(accountId) { return `${WECHAT_BIND_CACHE_PREFIX}${accountId}`; } getWechatBindCodeCacheKey(code) { return `${WECHAT_BIND_CODE_CACHE_PREFIX}${code}`; } getWechatBindScanCacheKey(code) { return `${WECHAT_BIND_SCAN_CACHE_PREFIX}${code}`; } getWechatLoginClientCacheKey(clientCode) { return `${WECHAT_LOGIN_CLIENT_CACHE_PREFIX}${clientCode}`; } getWechatLoginCodeCacheKey(code) { return `${WECHAT_LOGIN_CODE_CACHE_PREFIX}${code}`; } getWechatLoginEventChannel(clientCode) { return `${WECHAT_LOGIN_EVENT_CHANNEL_PREFIX}${clientCode}`; } createWechatBindCodeCandidate() { const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; let code = ''; for (let i = 0; i < 6; i++) { const index = crypto.randomInt(0, charset.length); code += charset[index]; } return code; } async createUniqueSixCode(getCacheKey, maxAttempts = 200) { for (let attempt = 0; attempt < maxAttempts; attempt++) { const code = this.createWechatBindCodeCandidate(); if (!this.parseWechatBindCode(code)) { continue; } const cacheKey = getCacheKey(code); const existsState = await this.app.getCacheAsync(cacheKey); if (!existsState) { return code; } } throw new Error('生成登录码失败,请稍后重试'); } async createWechatBindCode(maxAttempts = 200) { return await this.createUniqueSixCode(this.getWechatBindCodeCacheKey.bind(this), maxAttempts); } async createWechatLoginCode(maxAttempts = 200) { return await this.createUniqueSixCode(this.getWechatLoginCodeCacheKey.bind(this), maxAttempts); } async createWechatLoginClientCode(maxAttempts = 200) { return await this.createUniqueSixCode(this.getWechatLoginClientCacheKey.bind(this), maxAttempts); } parseWechatBindCode(code) { const normalized = typeof code === 'string' ? code.trim().toUpperCase() : ''; if (!normalized) { return null; } if (!/^[A-Z0-9]{6}$/.test(normalized)) { return null; } if (!/[A-Z]/.test(normalized) || !/[0-9]/.test(normalized)) { return null; } return normalized; } formatBindWechatData(state, source = 'db') { const expiresAt = Number(state.expires_at || 0); return { account_id: state.account_id, code: state.code || '', status: state.status || 'pending', is_bound: state.status === 'bound', updated_at: state.updated_at || new Date().toISOString(), expires_at: expiresAt > 0 ? expiresAt : null, expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, scanned_at: state.scanned_at || null, source, ye4s_user_id: state.ye4s_user_id || null, }; } formatLoginWechatData(state, source = 'cache') { const expiresAt = Number(state.expires_at || 0); return { client_code: state.client_code || '', code: state.code || '', status: state.status || 'pending', updated_at: state.updated_at || new Date().toISOString(), expires_at: expiresAt > 0 ? expiresAt : null, expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, source, }; } getRemainingSecondsByExpiresAt(expiresAt, fallbackTtl = WECHAT_BIND_CACHE_TTL_SECONDS) { const ts = Number(expiresAt); if (!Number.isFinite(ts) || ts <= 0) { return fallbackTtl; } return Math.max(1, Math.ceil((ts - Date.now()) / 1000)); } async setWechatBindCache(cacheKey, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { await this.app.setCacheAsync(cacheKey, state, ttl); } async setWechatBindCodeCache(code, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { if (!code) { return; } const codeCacheKey = this.getWechatBindCodeCacheKey(code); await this.app.setCacheAsync(codeCacheKey, state, ttl); } async setWechatBindScanCache(code, state, ttl = WECHAT_BIND_SCAN_CACHE_TTL_SECONDS) { if (!code) { return; } const scanCacheKey = this.getWechatBindScanCacheKey(code); await this.app.setCacheAsync(scanCacheKey, state, ttl); } async getWechatBindScanCache(code) { if (!code) { return null; } const scanCacheKey = this.getWechatBindScanCacheKey(code); return await this.app.getCacheAsync(scanCacheKey); } async setWechatLoginClientCache(clientCode, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { if (!clientCode) { return; } const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); await this.app.setCacheAsync(clientCacheKey, state, ttl); } async setWechatLoginCodeCache(code, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { if (!code) { return; } const codeCacheKey = this.getWechatLoginCodeCacheKey(code); await this.app.setCacheAsync(codeCacheKey, state, ttl); } async findYe4sBindingByAccountId(accountId) { const { ctx } = this; const ye4sClient = ctx.app.mysql.get('ye4s'); const rows = await ye4sClient.select('ye4s_user', { where: { wms_account_id: accountId, }, columns: [ 'id', 'tmp_code', 'wms_account_id' ], orders: [[ 'id', 'desc' ]], limit: 1, }); if (!rows || rows.length === 0) { return null; } return rows[0]; } getWechatBindEventChannel(accountId) { return `${WECHAT_BIND_EVENT_CHANNEL_PREFIX}${accountId}`; } getWechatLongPollTimeoutMs(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { const waitMs = Number(timeoutMs); if (Number.isFinite(waitMs) && waitMs > 0) { return Math.floor(waitMs); } return WECHAT_BIND_LONG_POLL_TIMEOUT_MS; } shouldUseWechatBindLongPoll(data = {}) { return data.longPoll === true; } async publishWechatBindEvent(accountId, payload = {}) { const { app } = this; if (!accountId) { return; } const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; if (!cacheRedis) { return; } const channel = this.getWechatBindEventChannel(accountId); const eventData = { account_id: accountId, event_at: new Date().toISOString(), ...payload, }; try { await cacheRedis.publish(channel, JSON.stringify(eventData)); } catch (error) { app.coreLogger.warn(`发布微信绑定事件失败: ${error.message}`); } } /** * 发布微信登录事件(唤醒 user.getLoginWechatCode 打开的长轮询)。 * * @param {string} clientCode 客户端编码。 * @param {object} [payload={}] 附加事件数据(如 ye4s_user_id)。 * @return {Promise} 无返回值。 */ async publishWechatLoginEvent(clientCode, payload = {}) { const { app } = this; if (!clientCode) { return; } const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; if (!cacheRedis) { return; } const channel = this.getWechatLoginEventChannel(clientCode); const eventData = { client_code: clientCode, event_at: new Date().toISOString(), ...payload, }; try { await cacheRedis.publish(channel, JSON.stringify(eventData)); } catch (error) { app.coreLogger.warn(`发布微信登录事件失败: ${error.message}`); } } async waitForWechatBindEvent(accountId, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { const { app } = this; const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; if (!cacheRedis || !accountId || typeof cacheRedis.duplicate !== 'function') { return { timed_out: true, reason: 'redis_not_available', }; } const channel = this.getWechatBindEventChannel(accountId); const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); const subscriber = cacheRedis.duplicate(); return await new Promise(resolve => { let settled = false; let timer = null; function onMessage(messageChannel, message) { if (messageChannel !== channel) { return; } let eventData = null; try { eventData = message ? JSON.parse(message) : null; } catch (error) { eventData = { raw: message }; } finalize({ timed_out: false, reason: 'event', event: eventData, }); } function onError(error) { app.coreLogger.warn(`订阅微信绑定事件失败: ${error.message}`); finalize({ timed_out: true, reason: 'subscribe_error', }); } function finalize(result) { if (settled) { return; } settled = true; if (timer) { clearTimeout(timer); } cleanup(); resolve(result); } function cleanup() { subscriber.removeListener('message', onMessage); subscriber.removeListener('error', onError); Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { if (typeof subscriber.quit === 'function') { Promise.resolve(subscriber.quit()).catch(() => { if (typeof subscriber.disconnect === 'function') { subscriber.disconnect(); } }); return; } if (typeof subscriber.disconnect === 'function') { subscriber.disconnect(); } }); } timer = setTimeout(() => { finalize({ timed_out: true, reason: 'timeout', }); }, waitMs); subscriber.on('message', onMessage); subscriber.on('error', onError); Promise.resolve(subscriber.subscribe(channel)).catch(error => { app.coreLogger.warn(`订阅微信绑定频道失败: ${error.message}`); finalize({ timed_out: true, reason: 'subscribe_failed', }); }); }); } async refreshWechatBindState(accountId, cachedState = null, options = {}) { const now = Date.now(); const cacheKey = this.getWechatBindCacheKey(accountId); const forceNewCode = options.forceNewCode === true; const ye4sBinding = await this.findYe4sBindingByAccountId(accountId); if (ye4sBinding) { const boundState = { account_id: accountId, status: 'bound', code: '', updated_at: new Date().toISOString(), ye4s_user_id: ye4sBinding.id || null, expires_at: null, scanned_at: null, }; await this.setWechatBindCache(cacheKey, boundState, WECHAT_BIND_CACHE_TTL_SECONDS); const hasChanged = !cachedState || cachedState.status !== 'bound' || Number(cachedState.ye4s_user_id || 0) !== Number(boundState.ye4s_user_id || 0); if (hasChanged) { await this.publishWechatBindEvent(accountId, { status: 'bound', code: '', source: 'db', }); } return { state: boundState, source: 'db', message: '账号已绑定微信', }; } const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; let codeState = null; if (!forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode)) { const codeCacheKey = this.getWechatBindCodeCacheKey(cachedCode); codeState = await this.app.getCacheAsync(codeCacheKey); } const codeAccountId = Number(codeState && codeState.account_id); const cachedExpiresAt = Number((codeState && codeState.expires_at) || (cachedState && cachedState.expires_at)); const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(codeAccountId) && codeAccountId === accountId && (Number.isFinite(cachedExpiresAt) ? cachedExpiresAt > now : !!codeState); if (cachedCodeValid) { const scanState = await this.getWechatBindScanCache(cachedCode); const normalizedStatus = scanState ? 'scanned' : 'pending'; const state = { account_id: accountId, status: normalizedStatus, code: cachedCode, updated_at: cachedState.updated_at || new Date().toISOString(), ye4s_user_id: null, expires_at: Number.isFinite(cachedExpiresAt) ? cachedExpiresAt : null, scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, }; return { state, source: 'cache', message: normalizedStatus === 'scanned' ? '二维码已被扫码,请继续绑定' : '获取绑定码成功(缓存)', }; } const nextCode = await this.createWechatBindCode(); const expiresAt = now + WECHAT_BIND_CACHE_TTL_SECONDS * 1000; const pendingState = { account_id: accountId, status: 'pending', code: nextCode, updated_at: new Date().toISOString(), ye4s_user_id: null, expires_at: expiresAt, scanned_at: null, }; const tasks = [ this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), this.setWechatBindCodeCache(nextCode, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), ]; if (cachedCode && cachedCode !== nextCode) { tasks.push(this.setWechatBindCodeCache(cachedCode, null, 1)); tasks.push(this.setWechatBindScanCache(cachedCode, null, 1)); } await Promise.all(tasks); return { state: pendingState, source: forceNewCode ? 'refreshed' : 'generated', message: forceNewCode ? '长轮询超时,已刷新绑定码' : '账号未绑定,已生成绑定码', }; } /** * 用户登录(重构版) * @param {string} username - 用户名/手机号/邮箱 * @param {string} password - 密码 * @param {string} loginType - 登录类型: username, phone, email, auto * @return {Object} 登录结果 */ async login(username, password, loginType = 'auto') { const { 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; } // 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); return this.buildLoginResult(user, { includeUser: false }); } catch (error) { app.coreLogger.error(`登录异常: ${error.message}`); return { success: false, data: null, code: 0, message: '用户名或密码错误或账号状态异常', }; } } /** * 登录码登录:使用Ye4s登录码进行登录 * @param {string} code 登录码(WECHAT_LOGIN_CODE) * @return {Object} 登录结果 */ async loginByYe4sCode(code) { const { ctx, app } = this; try { const rawCode = typeof code === 'string' ? code.trim() : ''; if (!rawCode) { return { success: false, data: null, code: 0, message: '缺少或无效的登录码 code', }; } const candidateSet = new Set([ rawCode ]); try { const decoded = Buffer.from(rawCode, 'base64').toString('utf8').trim(); if (decoded) { candidateSet.add(decoded); if (decoded.startsWith('{') && decoded.endsWith('}')) { const parsed = JSON.parse(decoded); const possibleCode = [ parsed && parsed.uuid, parsed && parsed.tmp_code, parsed && parsed.code ] .map(item => (typeof item === 'string' ? item.trim() : '')) .filter(Boolean); for (const item of possibleCode) { candidateSet.add(item); } } } } catch (decodeErr) { // 非 base64/JSON 登录码时忽略解码失败,继续使用原始 code。 } const codeCandidates = Array.from(candidateSet).filter(item => typeof item === 'string' && item.length > 0); if (codeCandidates.length === 0) { return { success: false, data: null, code: 0, message: '缺少或无效的登录码 code', }; } const ye4sClient = ctx.app.mysql.get('ye4s'); const rows = await ye4sClient.select('ye4s_user', { where: { tmp_code: codeCandidates, }, columns: [ 'id', 'tmp_code', 'wms_account_id' ], orders: [[ 'id', 'DESC' ]], limit: 1, }); if (!rows || rows.length === 0) { return { success: false, data: null, code: 0, message: '登录码不存在或已过期', }; } const ye4sUserId = Number(rows[0].id); if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) { return { success: false, data: null, code: 0, message: '登录码对应用户无效', }; } return await this.loginByYe4sUserId(ye4sUserId); } catch (error) { app.coreLogger.error(`登录码登录异常: ${error.message}`); return { success: false, data: null, code: 0, message: '登录失败,请稍后重试', }; } } async waitForLoginCodeRefresh(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); await new Promise(resolve => { setTimeout(resolve, waitMs); }); } isTransientWechatLoginError(error) { if (!error) { return false; } const code = typeof error.code === 'string' ? error.code : ''; const message = typeof error.message === 'string' ? error.message.toLowerCase() : ''; const transientCodes = new Set([ 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'PROTOCOL_CONNECTION_LOST', 'ECONNREFUSED' ]); if (transientCodes.has(code)) { return true; } return message.includes('econnreset') || message.includes('read econnreset') || message.includes('connection lost') || message.includes('timeout'); } extractYe4sUserIdFromLoginEvent(eventData) { if (!eventData) { return null; } if (typeof eventData === 'number' || typeof eventData === 'string') { const id = Number(eventData); return Number.isFinite(id) && id > 0 ? id : null; } if (typeof eventData !== 'object') { return null; } const rawId = eventData.ye4s_user_id ?? eventData.ye4sUserId ?? eventData.user_id ?? eventData.userId ?? eventData.value; const ye4sUserId = Number(rawId); return Number.isFinite(ye4sUserId) && ye4sUserId > 0 ? ye4sUserId : null; } /** * 等待微信登录事件并解析事件中的 ye4s 用户 ID。 * @param {string} clientCode 客户端编码 * @param {number} timeoutMs 等待超时时间,单位为毫秒 * @return {Promise} 事件监听结果 */ async waitForWechatLoginEvent(clientCode, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { const { app } = this; const normalizedClientCode = this.parseWechatBindCode(clientCode); const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; if (!cacheRedis || !normalizedClientCode || typeof cacheRedis.duplicate !== 'function') { return { timed_out: true, reason: 'redis_not_available', event: null, }; } const channel = this.getWechatLoginEventChannel(normalizedClientCode); const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); const subscriber = cacheRedis.duplicate(); return await new Promise(resolve => { let settled = false; let timer = null; const onMessage = (messageChannel, message) => { if (messageChannel !== channel) { return; } let eventData = null; try { eventData = message ? JSON.parse(message) : null; } catch (error) { eventData = message; } const ye4sUserId = this.extractYe4sUserIdFromLoginEvent(eventData); finalize({ timed_out: false, reason: 'event', event: eventData, ye4s_user_id: ye4sUserId, }); }; function onError(error) { app.coreLogger.warn(`订阅微信登录事件失败: ${error.message}`); finalize({ timed_out: true, reason: 'subscribe_error', event: null, }); } function finalize(result) { if (settled) { return; } settled = true; if (timer) { clearTimeout(timer); } cleanup(); resolve(result); } function cleanup() { subscriber.removeListener('message', onMessage); subscriber.removeListener('error', onError); Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { if (typeof subscriber.quit === 'function') { Promise.resolve(subscriber.quit()).catch(() => { if (typeof subscriber.disconnect === 'function') { subscriber.disconnect(); } }); return; } if (typeof subscriber.disconnect === 'function') { subscriber.disconnect(); } }); } timer = setTimeout(() => { finalize({ timed_out: true, reason: 'timeout', event: null, }); }, waitMs); subscriber.on('message', onMessage); subscriber.on('error', onError); Promise.resolve(subscriber.subscribe(channel)).catch(error => { app.coreLogger.warn(`订阅微信登录频道失败: ${error.message}`); finalize({ timed_out: true, reason: 'subscribe_failed', event: null, }); }); }); } async loginByYe4sUserId(ye4sUserId) { const { ctx, app } = this; const normalizedYe4sUserId = Number(ye4sUserId); if (!Number.isFinite(normalizedYe4sUserId) || normalizedYe4sUserId <= 0) { return { success: false, code: 0, data: null, message: '登录事件缺少有效的 ye4s_user_id', }; } const maxAttempts = 2; for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { const ye4sClient = ctx.app.mysql.get('ye4s'); const ye4sUser = await ye4sClient.get('ye4s_user', { id: normalizedYe4sUserId }); if (!ye4sUser) { return { success: false, code: 0, data: null, message: 'ye4s 用户不存在', }; } const wmsAccountId = Number(ye4sUser.wms_account_id); if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) { return { success: false, code: 0, data: null, message: '该 ye4s 用户未绑定WMS账号', }; } const user = await ctx.model.Account.findOne({ where: { id: wmsAccountId }, }); if (!user) { return { success: false, code: 0, data: null, message: '绑定的WMS账号不存在', }; } try { this.checkUserStatus(user); } catch (statusError) { app.coreLogger.warn(`微信事件登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`); return { success: false, code: 0, data: null, message: '绑定账号状态异常', }; } await this.updateLastLoginTime(user.id); const loginResult = await this.buildLoginResult(user, { includeUser: false }); return loginResult; } catch (error) { const isTransient = this.isTransientWechatLoginError(error); if (isTransient && attempt < maxAttempts) { app.coreLogger.warn(`微信事件登录异常,准备重试(${attempt}/${maxAttempts}): ${error.message}`); await this.waitForLoginCodeRefresh(200); continue; } app.coreLogger.error(`微信事件登录异常: ${error.message}`); return { success: false, code: 0, data: null, message: '登录失败,请稍后重试', }; } } return { success: false, code: 0, data: null, message: '登录失败,请稍后重试', }; } async tryBuildWechatLoginTokenFromState(clientCode, state) { const eventYe4sUserId = this.extractYe4sUserIdFromLoginEvent(state); if (!Number.isFinite(Number(eventYe4sUserId)) || Number(eventYe4sUserId) <= 0) { return null; } const loginResult = await this.loginByYe4sUserId(eventYe4sUserId); if (!loginResult || !loginResult.success || !loginResult.data || !loginResult.data.token) { return { success: false, code: 0, data: null, message: loginResult && loginResult.message ? loginResult.message : '登录事件处理失败', }; } const cleanupCode = state && typeof state.code === 'string' ? state.code.trim().toUpperCase() : ''; await Promise.all([ this.setWechatLoginClientCache(clientCode, null, 1), cleanupCode ? this.setWechatLoginCodeCache(cleanupCode, null, 1) : Promise.resolve(), ]); return { success: true, code: 200, data: { client_code: clientCode, status: 'authorized', source: 'event', ye4s_user_id: Number(eventYe4sUserId), loginToken: loginResult.data.token, }, message: '已收到登录事件并签发登录令牌', }; } async refreshWechatLoginState(clientCode, cachedState = null, options = {}) { const now = Date.now(); const forceNewCode = options.forceNewCode === true; const normalizedClientCode = this.parseWechatBindCode(clientCode); if (!normalizedClientCode) { throw new Error('无效的客户端编码格式'); } const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; const cachedExpiresAt = Number(cachedState && cachedState.expires_at); const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(cachedExpiresAt) && cachedExpiresAt > now; if (cachedCodeValid) { return { state: { client_code: normalizedClientCode, code: cachedCode, status: 'pending', updated_at: cachedState.updated_at || new Date().toISOString(), expires_at: cachedExpiresAt, }, source: 'cache', message: `客户端编码 ${normalizedClientCode} 已命中缓存登录码`, }; } const nextCode = await this.createWechatLoginCode(); const expiresAt = now + WECHAT_LOGIN_CACHE_TTL_SECONDS * 1000; const loginState = { client_code: normalizedClientCode, code: nextCode, status: 'pending', updated_at: new Date().toISOString(), expires_at: expiresAt, }; const tasks = [ this.setWechatLoginClientCache(normalizedClientCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), this.setWechatLoginCodeCache(nextCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), ]; if (cachedCode && cachedCode !== nextCode) { tasks.push(this.setWechatLoginCodeCache(cachedCode, null, 1)); } await Promise.all(tasks); return { state: loginState, source: forceNewCode ? 'refreshed' : 'generated', message: forceNewCode ? `客户端编码 ${normalizedClientCode} 长轮询结束,已刷新登录码` : `客户端编码 ${normalizedClientCode} 已生成登录码`, }; } /** * 获取微信扫码登录码 * @param {Object} data 请求参数 * @return {Object} 登录码结果 */ async getLoginWechatCode(data = {}) { const { app } = this; try { const rawClientCode = typeof data.clientCode === 'string' ? data.clientCode : (typeof data.client_code === 'string' ? data.client_code : ''); const hasInputClientCode = !!rawClientCode && rawClientCode.trim().length > 0; let clientCode = ''; let shouldWaitRefresh = false; let cachedState = null; if (hasInputClientCode) { const normalizedClientCode = this.parseWechatBindCode(rawClientCode); if (!normalizedClientCode) { return { success: false, code: 0, data: null, message: '无效的客户端编码格式', }; } const inputClientCacheKey = this.getWechatLoginClientCacheKey(normalizedClientCode); try { cachedState = await this.app.getCacheAsync(inputClientCacheKey); } catch (cacheErr) { app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); } // 传入 clientCode 但缓存不存在时,按空值处理,重新分配新的客户端编码。 if (cachedState) { clientCode = normalizedClientCode; shouldWaitRefresh = true; } else { clientCode = await this.createWechatLoginClientCode(); } } else { clientCode = await this.createWechatLoginClientCode(); } const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); if (!cachedState) { try { cachedState = await this.app.getCacheAsync(clientCacheKey); } catch (cacheErr) { app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); } } // 若外部已将 ye4s_user_id 写入 clientCode 对应缓存,直接登录并返回,不再等待长轮询。 if (hasInputClientCode && cachedState) { const immediateLoginResult = await this.tryBuildWechatLoginTokenFromState(clientCode, cachedState); if (immediateLoginResult && immediateLoginResult.success) { return immediateLoginResult; } if (immediateLoginResult && immediateLoginResult.success === false) { app.coreLogger.warn(`微信登录缓存态直登失败,继续轮询: ${immediateLoginResult.message}`); } } if (shouldWaitRefresh) { const waitResult = await this.waitForWechatLoginEvent(clientCode, this.getWechatLongPollTimeoutMs()); const eventYe4sUserId = Number(waitResult && waitResult.ye4s_user_id); if (!waitResult.timed_out && Number.isFinite(eventYe4sUserId) && eventYe4sUserId > 0) { const eventState = { ...(cachedState || {}), ye4s_user_id: eventYe4sUserId, }; const loginResponse = await this.tryBuildWechatLoginTokenFromState(clientCode, eventState); if (loginResponse && loginResponse.success) { return loginResponse; } app.coreLogger.warn(`微信事件登录未成功,降级为刷新登录码: ${loginResponse && loginResponse.message ? loginResponse.message : 'unknown_error'}`); } try { cachedState = await this.app.getCacheAsync(clientCacheKey); } catch (cacheErr) { app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); } const refreshed = await this.refreshWechatLoginState(clientCode, cachedState, { forceNewCode: true, }); return { success: true, code: 200, data: this.formatLoginWechatData(refreshed.state, refreshed.source), message: refreshed.message, }; } const generated = await this.refreshWechatLoginState(clientCode, cachedState, { forceNewCode: false, }); return { success: true, code: 200, data: this.formatLoginWechatData(generated.state, generated.source), message: generated.message, }; } catch (error) { app.coreLogger.error(`获取微信登录码失败: ${error.message}`); return { success: false, code: 0, data: null, message: '获取微信登录码失败,请稍后重试', }; } } /** * 获取微信绑定码(缓存优先,低频复查DB,适配轮询) * @param {Object} data 请求参数 * @return {Object} 绑定码结果 */ async getBindWechatCode(data = {}) { const accountId = this.getCurrentAccountId(); return await this.getBindWechatCodeByAccountId(accountId, data, { missingAccountMessage: '未识别到登录账号,无法生成绑定码', }); } async getBindWechatCodeByAccountId(accountId, data = {}, options = {}) { const { app } = this; try { const normalizedAccountId = Number(accountId); if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) { return { success: false, code: 0, data: null, message: options.missingAccountMessage || '未识别到目标账号,无法生成绑定码', }; } const cacheKey = this.getWechatBindCacheKey(normalizedAccountId); const useLongPoll = this.shouldUseWechatBindLongPoll(data); const waitTimeoutMs = this.getWechatLongPollTimeoutMs(); let cachedState = null; try { cachedState = await this.app.getCacheAsync(cacheKey); } catch (cacheErr) { app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); } const refreshed = await this.refreshWechatBindState(normalizedAccountId, cachedState, { forceNewCode: false, }); if (refreshed.state.status === 'bound' || !useLongPoll) { return { success: true, code: 200, data: this.formatBindWechatData(refreshed.state, refreshed.source), message: refreshed.message, }; } const waitResult = await this.waitForWechatBindEvent(normalizedAccountId, waitTimeoutMs); try { cachedState = await this.app.getCacheAsync(cacheKey); } catch (cacheErr) { app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); } const nextState = await this.refreshWechatBindState(normalizedAccountId, cachedState, { forceNewCode: waitResult.timed_out, }); if (waitResult.timed_out) { return { success: true, code: 200, data: this.formatBindWechatData(nextState.state, nextState.source), message: '长轮询结束未检测到状态变化,已刷新绑定码', }; } return { success: true, code: 200, data: this.formatBindWechatData(nextState.state, nextState.source), message: nextState.message, }; } catch (error) { app.coreLogger.error(`获取微信绑定码失败: ${error.message}`); return { success: false, code: 0, data: null, message: '获取绑定码失败,请稍后重试', }; } } /** * 根据绑定临时码获取账号ID(供 ye4s 扫码绑定调用) * @param {Object} data 请求参数 * @return {Object} 账号查询结果 */ async getUserByTempCode(data = {}) { const { ctx, app } = this; try { const loadAccountRealName = async accountId => { const account = await ctx.model.Account.findOne({ where: { id: accountId, }, attributes: [ 'id', 'real_name' ], raw: true, }); return account && account.real_name ? account.real_name : ''; }; const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; if (!rawCode) { return { success: false, code: 0, data: null, message: '缺少绑定码 code', }; } const code = this.parseWechatBindCode(rawCode); if (!code) { return { success: false, code: 0, data: null, message: '无效的绑定码格式', }; } const codeCacheKey = this.getWechatBindCodeCacheKey(code); let codeState = null; try { codeState = await this.app.getCacheAsync(codeCacheKey); } catch (cacheErr) { app.coreLogger.warn(`读取绑定码映射缓存失败: ${cacheErr.message}`); } const cachedAccountId = Number(codeState && codeState.account_id); if (!Number.isFinite(cachedAccountId) || cachedAccountId <= 0) { return { success: false, code: 0, data: null, message: '绑定码不存在或已过期', }; } const realName = await loadAccountRealName(cachedAccountId); const scanState = { account_id: cachedAccountId, code, status: 'scanned', scanned_at: new Date().toISOString(), source: 'gateway-scan', }; const codeExpiresAt = Number(codeState && codeState.expires_at); const scannedBindState = { account_id: cachedAccountId, code, status: 'scanned', scanned_at: scanState.scanned_at, updated_at: scanState.scanned_at, ye4s_user_id: null, expires_at: Number.isFinite(codeExpiresAt) ? codeExpiresAt : null, }; const bindCacheTtl = this.getRemainingSecondsByExpiresAt(codeExpiresAt, WECHAT_BIND_CACHE_TTL_SECONDS); await Promise.all([ this.setWechatBindScanCache(code, scanState, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), this.setWechatBindCache(this.getWechatBindCacheKey(cachedAccountId), scannedBindState, bindCacheTtl), ]); await this.publishWechatBindEvent(cachedAccountId, { status: 'scanned', code, scanned_at: scanState.scanned_at, source: 'gateway-scan', }); return { success: true, code: 200, data: { account_id: cachedAccountId, real_name: realName, code, status: 'scanned', source: 'scan-cache', scanned_at: scanState.scanned_at, updated_at: codeState && codeState.updated_at ? codeState.updated_at : scanState.scanned_at, }, message: '扫码状态已记录', }; } catch (error) { app.coreLogger.error(`根据绑定码获取账号失败: ${error.message}`); return { success: false, code: 0, data: null, message: '获取账号失败,请稍后重试', }; } } /** * 账号绑定:供 ye4s 扫码后回调,按临时码绑定到指定 ye4s_user.id * @param {Object} data 请求参数 * @return {Object} 绑定结果 */ async bindAccountByTempCode(data = {}) { const { ctx, app } = this; try { const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; const rawYe4sUserId = data.ye4s_user_id ?? data.ye4sUserId; const ye4sUserId = Number(rawYe4sUserId); if (!rawCode) { return { success: false, code: 0, data: null, message: '缺少绑定码 code', }; } const code = this.parseWechatBindCode(rawCode); if (!code) { return { success: false, code: 0, data: null, message: '无效的绑定码格式', }; } if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) { return { success: false, code: 0, data: null, message: '缺少有效的 ye4s_user_id', }; } const scanState = await this.getWechatBindScanCache(code); const accountId = Number(scanState && scanState.account_id); if (!Number.isFinite(accountId) || accountId <= 0) { return { success: false, code: 0, data: null, message: '未检测到扫码记录或扫码状态已过期,请重新扫码', }; } const ye4sClient = ctx.app.mysql.get('ye4s'); const ye4sUser = await ye4sClient.get('ye4s_user', { id: ye4sUserId }); if (!ye4sUser) { return { success: false, code: 0, data: null, message: 'ye4s 用户不存在', }; } const updateRet = await ye4sClient.update('ye4s_user', { id: ye4sUserId, wms_account_id: accountId, }); const boundState = { account_id: accountId, status: 'bound', code: '', updated_at: new Date().toISOString(), ye4s_user_id: ye4sUserId, expires_at: null, scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, }; await Promise.all([ this.setWechatBindCache(this.getWechatBindCacheKey(accountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), this.setWechatBindCodeCache(code, null, 1), this.setWechatBindScanCache(code, { ...scanState, status: 'bound', ye4s_user_id: ye4sUserId, bound_at: boundState.updated_at, }, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), ]); await this.publishWechatBindEvent(accountId, { status: 'bound', code: '', source: 'gateway-bind', }); return { success: true, code: 200, data: { account_id: accountId, ye4s_user_id: ye4sUserId, code, status: 'bound', source: 'gateway-bind', affected_rows: Number(updateRet && updateRet.affectedRows ? updateRet.affectedRows : 0), updated_at: boundState.updated_at, }, message: '绑定成功', }; } catch (error) { app.coreLogger.error(`账号绑定失败: ${error.message}`); return { success: false, code: 0, data: null, message: '绑定失败,请稍后重试', }; } } /** * 解绑微信:清理 ye4s_user 中与当前账号关联的数据 * @return {Object} 解绑结果 */ async unbindWechat() { const accountId = this.getCurrentAccountId(); return await this.unbindWechatByAccountId(accountId, { missingAccountMessage: '未识别到登录账号,无法解绑', }); } async unbindWechatByAccountId(accountId, options = {}) { const { ctx, app } = this; try { const normalizedAccountId = Number(accountId); if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) { return { success: false, code: 0, data: null, message: options.missingAccountMessage || '未识别到目标账号,无法解绑', }; } const ye4sClient = ctx.app.mysql.get('ye4s'); const bindRows = await ye4sClient.select('ye4s_user', { where: { wms_account_id: normalizedAccountId, }, columns: [ 'id', 'tmp_code', 'wms_account_id' ], orders: [[ 'id', 'desc' ]], limit: 500, }); let affectedRows = 0; for (const row of bindRows) { try { const ret = await ye4sClient.update('ye4s_user', { id: row.id, wms_account_id: null, }); affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0); } catch (err) { const ret = await ye4sClient.update('ye4s_user', { id: row.id, wms_account_id: 0, }); affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0); } } const cacheKey = this.getWechatBindCacheKey(normalizedAccountId); await this.setWechatBindCache(cacheKey, null, 1); await this.publishWechatBindEvent(normalizedAccountId, { status: 'unbound', source: 'unbind', }); return { success: true, code: 200, data: { account_id: normalizedAccountId, status: 'unbound', matched_rows: bindRows.length, affected_rows: affectedRows, updated_at: new Date().toISOString(), }, message: bindRows.length > 0 ? '解绑成功' : '当前账号未绑定微信', }; } catch (error) { app.coreLogger.error(`解绑微信失败: ${error.message}`); return { success: false, code: 0, data: null, message: '解绑失败,请稍后重试', }; } } /** * 生成统一登录成功结构 * @param {Object} user 用户对象 * @param {Object} options 登录选项 * @return {Object} 登录结果 */ async buildLoginResult(user, options = {}) { const { ctx, app } = this; const includeUser = options.includeUser !== false; // 设置设备类型(用于菜单查询) const platformCode = ctx.header.platform || 'web'; // 获取用户完整信息 const userInfo = await this.findById(user.id); if (!userInfo) { throw new Error('用户信息加载失败'); } // 如果用户有角色但当前平台没有激活角色,则自动设置一个 if (userInfo && userInfo.roles && userInfo.roles.length > 0 && !userInfo.role_id) { await this.ensurePlatformActiveRole(user.id, userInfo.roles[0].id, platformCode); } // 生成 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, }); const payloadData = { token, }; if (includeUser) { payloadData.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, }; } return { success: true, data: payloadData, code: 200, message: '登录成功', }; } /** * 切换角色(重构版) * @param {Object} data 切换角色数据 * @return {Object} 切换结果 */ async changeRole(data) { const { ctx, app } = this; const user = ctx.state.user || ctx.user; try { // 验证角色关联是否存在且有效 const accountStoreEmployee = await ctx.model.AccountStoreEmployee.findOne({ where: { id: data.roleId, account_id: user.id, status: 1, }, include: [ { model: ctx.model.EmployeeRole, as: 'employeeRoles', }, ], }); if (!accountStoreEmployee) { 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: accountStoreEmployee.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={}] 入参。 * @param {string} [data.wechat_appId] 小程序 AppID:传入时按该小程序归属仓库过滤工号列表, * 仅保留非仓库工号(货主)与该仓库工号;未传入/查不到仓库时保持原逻辑。 * @return {Object} 用户信息 */ async info(data = {}) { const { ctx } = this; try { // 微信登录态中间层:未绑定真实用户时返回微信层信息(不 401) if (!ctx.userId && !ctx.user && ctx.oauth) { const oauth = ctx.oauth; return { success: true, data: { id: Number(oauth.user_id) || 0, is_bound: Number(oauth.user_id) > 0, oauth_id: oauth.id, user_id: Number(oauth.user_id) || 0, openid: oauth.openid, unionid: oauth.unionid || '', nickname: oauth.nickname || '', headimgurl: oauth.headimgurl || '', login_time: oauth.login_time, login_count: oauth.login_count, }, code: 200, }; } const userId = ctx.userId || (ctx.user && ctx.user.id); const user = await this.findById(userId); if (!user) { return { success: false, data: null, code: 401, }; } // 可选:传入 wechat_appId 时按小程序归属仓库过滤工号列表 // (只保留非仓库工号(货主)与仅该仓库工号) const appId = typeof data.wechat_appId === 'string' ? data.wechat_appId.trim() : ''; if (appId) { const wechatApp = await ctx.model.WechatApp.findOne({ where: { appid: appId, is_enabled: 1 }, attributes: [ 'id', 'appid', 'warehouse_id' ], }); const warehouseId = Number(wechatApp && wechatApp.warehouse_id); if (wechatApp && Number.isInteger(warehouseId) && warehouseId > 0 && Array.isArray(user.employees)) { user.employees = user.employees.filter( employee => String(employee.role_type) !== 'warehouse' || Number(employee.store_id) === warehouseId ); } } return { success: true, data: user, code: 200, }; } catch (error) { return { success: false, data: null, code: 0, }; } } /** * 查找用户所有的角色以及对应的主体(重构版) * @param {number} userId 用户ID * @return {Promise} 角色列表 */ async getRoles(userId) { const { ctx } = this; const platformCode = ctx.header.platform || 'web'; const project = ctx.header.project || 'all'; try { const loadAccountStoreEmployees = async projectFilter => { const store_where = { status: 1, }; if (projectFilter && projectFilter !== 'all') { store_where.project = projectFilter; } return ctx.model.AccountStoreEmployee.findAll({ where: { account_id: userId, status: 1, }, include: [ { model: ctx.model.EmployeeRole, as: 'employeeRoles', attributes: [ 'id', 'role_id' ], }, { model: ctx.model.Store, as: 'store', attributes: [ 'id', 'company_name', 'project', 'auth_end' ], where: store_where, }, ], order: [[ 'created_at', 'DESC' ]], }); }; // 先按请求 project 过滤;查不到时降级到 all,便于补齐平台激活记录。 let accountStoreEmployees = await loadAccountStoreEmployees(project); if ((!accountStoreEmployees || accountStoreEmployees.length === 0) && project && project !== 'all') { accountStoreEmployees = await loadAccountStoreEmployees('all'); } if (!accountStoreEmployees || accountStoreEmployees.length === 0) { return { Employees: [], activeEmployeeId: null, menus: [], permissions: [], userRole: '', realName: null, }; } // 获取当前平台的激活角色 let activeEmployeeId = null; let realName = null; let userRole = ''; let currentPlatformEmployeeId = null; const platformActive = await ctx.model.AccountPlatformActive.findOne({ where: { account_id: userId, platform_code: platformCode, }, attributes: [ 'account_id', 'employee_id', 'platform_code' ], }); if (platformActive) { currentPlatformEmployeeId = platformActive.employee_id; } // 转换数据格式 const Employees = accountStoreEmployees.map(item => ({ id: item.id, store_id: item.store_id, store_name: item.store.company_name, is_primary: currentPlatformEmployeeId === 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); const permissions = await this.getPermissions(activeEmployeeId); return { Employees, activeEmployeeId, menus, permissions, userRole, realName }; } catch (error) { console.error('获取用户角色失败:', error); return { Employees: [], activeEmployeeId: null, menus: [], permissions: [], userRole: '', realName: null, }; } } /** * 根据ID查找用户(重构版) * @param {number} userId 用户ID * @param {boolean} useCache 是否使用缓存 * @return {Promise} 用户信息 */ async findById(userId, useCache = true) { const { ctx } = this; const platformCode = ctx.header.platform || 'web'; ctx.query_count++; try { // 生成缓存key const cacheKey = `user:info:${userId}:${platformCode}`; // 1. 尝试从缓存获取 if (useCache) { try { const cachedUser = await this.app.getCacheAsync(cacheKey); if (cachedUser) { 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. 获取角色信息(这个方法内部也有缓存逻辑) let { Employees, activeEmployeeId, menus, permissions, userRole } = await this.getRoles(userId); // pda 场景若缺少激活角色,优先补一条当前平台激活记录,避免直接报错。 if (platformCode === 'pda' && !activeEmployeeId && Employees.length > 0) { const fallbackEmployee = Employees[0]; await this.ensurePlatformActiveRole(userId, fallbackEmployee.id, platformCode); activeEmployeeId = fallbackEmployee.id; userRole = fallbackEmployee.role_type === 1 ? 'warehouse' : 'customer'; menus = await this.getMenus(activeEmployeeId); permissions = await this.getPermissions(activeEmployeeId); } // 4. 获取当前角色对应的仓库ID let storeId = null; let storeName = null; let storeCode = null; let storeType = 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; storeType = currentRole.role_type; roleName = currentRole.role_name; employees_name = currentRole.real_name; auth_end = currentRole.auth_end; } } const avatar = await this.getAvatarByEmployeeId(activeEmployeeId); if (platformCode === 'pda' && !activeEmployeeId) { ctx.logger.warn(`pda 平台未找到可激活角色,accountId=${userId},将以空角色上下文返回`); } // 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, store_type: storeType, menus, permissions, userRole, platform_code: platformCode, avatar, cached_at: new Date().toISOString(), }; // 6. 设置缓存 if (useCache) { await this.setUserCache(cacheKey, userInfo, 300); // 缓存5分钟 } return userInfo; } catch (error) { console.error('根据ID查找用户失败:', error); return null; } } /** * 设置用户缓存 * @param {string} cacheKey 缓存键 * @param {Object|null} userInfo 用户信息 * @param {number} ttl 缓存时间 * @private */ async setUserCache(cacheKey, userInfo, ttl = 300) { try { // 移除缓存标识字段 if (userInfo) { const cacheData = { ...userInfo }; delete cacheData.cached_at; 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 } = this; 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 {number} userId 用户ID * @param {string|null} 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', 'workerstation', 'workstation' ]; for (const platform of platforms) { const cacheKey = `user:info:${userId}:${platform}`; await this.app.setCacheAsync(cacheKey, null, 1); } } // 同时清除相关的缓存 await this.clearRelatedCache(userId); return true; } catch (error) { console.warn('清除用户缓存失败:', error.message); return false; } } /** * 清除用户相关缓存 * @param {number} userId 用户ID * @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} activeEmployeeId 员工ID * @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({ attributes: [ 'role_id' ], where: { employee_id: activeEmployeeId, }, include: [ { model: ctx.model.Role, as: 'role', attributes: [], where: { status: 1, }, required: true, }, ], raw: true, // 获取纯数据对象 }); if (!roles || roles.length === 0) { return []; } const roleIds = [ ...new Set(roles.map(item => item.role_id).filter(Boolean)) ]; if (roleIds.length === 0) { return []; } // 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表) const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { includeDisabled: false, }); if (permissionIds.length === 0) { return []; } const permissions = await ctx.model.Permission.findAll({ where: { id: { [Op.in]: permissionIds, }, status: 1, // 页面权限(`*_pages`)仅用于菜单路由,不应出现在接口权限集合中,包含 workerstation_pages。 type: { [ctx.app.Sequelize.Op.notLike]: '%_pages', }, }, attributes: [ 'id', 'path', 'type' ], order: [ [ 'sort', 'ASC' ], ], }); if (!permissions) { return []; } return permissions.map(item => item.path); } catch (error) { console.error('获取权限列表失败:', error); return []; } } /** * 获取当前员工菜单 * @param {number} activeEmployeeId 员工ID * @return {Promise} 菜单路由列表 */ async getMenus(activeEmployeeId) { const { ctx, app } = this; const { Sequelize } = app; const { Op } = Sequelize; if (!ctx.header.platform || !activeEmployeeId) { return []; } try { // 1. 获取员工绑定且启用的角色 const roles = await ctx.model.EmployeeRole.findAll({ attributes: [ 'role_id' ], where: { employee_id: activeEmployeeId, }, include: [ { model: ctx.model.Role, as: 'role', attributes: [], where: { status: 1, }, required: true, }, ], raw: true, // 获取纯数据对象 }); if (!roles || roles.length === 0) { return []; } const roleIds = [ ...new Set(roles.map(item => item.role_id).filter(Boolean)) ]; if (roleIds.length === 0) { return []; } // 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表) const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { includeDisabled: false, }); if (permissionIds.length === 0) { return []; } // 3. 获取权限对应的菜单(根据平台权限类型策略筛选) const menuTypeWhere = this.getMenuTypeWhereByPlatform(ctx.header.platform); const permissions = await ctx.model.Permission.findAll({ where: { id: { [Op.in]: permissionIds, }, status: 1, ...menuTypeWhere, }, order: [ [ 'sort', 'ASC' ], ], }); if (!permissions || permissions.length === 0) { return []; } return this.convertToRoutes(permissions); } catch (error) { ctx.logger.error('获取菜单列表失败:', error); return []; } } /** * 转换权限为路由格式(保持不变) * @param {Array} 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) { 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 rest = { ...node }; delete rest.id; delete rest.sort; if (rest.children && rest.children.length > 0) { rest.children = rest.children.map(child => cleanNode(child)); } return rest; }; return roots.map(root => cleanNode(root)); } /** * 根据标识符查找用户(已重构) * @param {string} identifier 标识符 * @param {string} type 查找类型 * @return {Promise} 用户对象 */ async findUserByIdentifier(identifier, type = 'auto') { const { ctx } = this; let user; if (type === 'auto') { // 自动判断类型 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 {Object} 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 {string} inputPassword 输入密码 * @param {string} storedHash 存储哈希 * @param {string} 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 {string} password 密码 * @param {string} 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 {number} userId 用户ID */ async updateLastLoginTime(userId) { const { ctx } = this; 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 {number} accountId 账号ID * @param {number} accountStoreRoleId 角色关联ID * @param {string} 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 {Object} userInfo 用户信息 * @param {Object|null} transaction 可选事务对象,传入时 Account.create 将在事务内执行 */ async register(userInfo, transaction = null) { const { ctx } = 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, }, transaction ? { transaction } : {}); return { userId: user.id, username: user.username, code: 200, message: '注册成功', }; } } module.exports = UserService;