'use strict'; const Service = require('egg').Service; const { parseWhereConditions } = require('../lib/query_condition_parser'); class MainService extends Service { constructor(ctx) { super(ctx); // 初始化公共变量 this.storeId = null; this.warehouseId = null; this.appKey = null; this.customerId = null; this.warehouseCode = null; this.commonData = {}; // 额外的公共数据存储 this._noNeedLogin = null; this._noNeedRight = null; this._noNeedAuth = null; this.user = null; this.userId = null; } success(message, data, code = 1) { const result = { flag: 'success', code, message, ...data, }; return result; } fail(message, data, code = 0) { const result = { flag: 'failure', code, message, ...data, }; return result; } normalizeDate(date, isEnd = false) { if (!date) return null; let d; if (date instanceof Date) { d = date; } else { // 尝试解析日期字符串 d = new Date(date); if (isNaN(d.getTime())) { return date; } } // 获取本地时间的年月日 const year = d.getFullYear(); const month = String(d.getMonth() + 1).padStart(2, '0'); const day = String(d.getDate()).padStart(2, '0'); // 根据 isEnd 参数添加时间部分 // 使用本地时间格式,避免时区转换 if (isEnd) { return `${year}-${month}-${day} 23:59:59`; } return `${year}-${month}-${day} 00:00:00`; } setInfo(storeId, warehouseId, appKey, customerId, warehouseCode) { this.storeId = storeId; this.warehouseId = warehouseId; this.appKey = appKey; this.warehouseCode = warehouseCode; this.customerId = customerId; } getInfo() { return { storeId: this.storeId, warehouseId: this.warehouseId, appKey: this.appKey, warehouseCode: this.warehouseCode, customerId: this.customerId, }; } isPlainObject(value) { return value && typeof value === 'object' && !Array.isArray(value); } normalizeWhereCondition(fieldKey, condition) { const isQuickWhere = fieldKey === 'quickWhere'; if (this.isPlainObject(condition)) { const hasStandardKeys = [ 'value', 'operator', 'type', 'field', 'values' ] .some(key => Object.prototype.hasOwnProperty.call(condition, key)); if (hasStandardKeys) { const normalized = { ...condition, }; if (!Object.prototype.hasOwnProperty.call(normalized, 'value') && Object.prototype.hasOwnProperty.call(normalized, 'values')) { normalized.value = normalized.values; delete normalized.values; } if (!Object.prototype.hasOwnProperty.call(normalized, 'operator') || !normalized.operator) { normalized.operator = Array.isArray(normalized.value) ? 'in' : (isQuickWhere ? 'like' : 'eq'); } if (isQuickWhere) { normalized.operator = normalized.operator || 'like'; normalized.type = normalized.type || 'text'; } if ((normalized.operator === 'between' || normalized.operator === 'notbetween') && this.isPlainObject(normalized.value)) { const start = normalized.value.start ?? normalized.value.from ?? normalized.value.begin; const end = normalized.value.end ?? normalized.value.to ?? normalized.value.finish; normalized.value = [ start, end ]; } return normalized; } } if (isQuickWhere) { return { operator: 'like', type: 'text', value: condition, }; } return { operator: Array.isArray(condition) ? 'in' : 'eq', value: condition, }; } normalizeWhereParams(whereInput = {}) { if (!this.isPlainObject(whereInput)) { return {}; } const normalized = {}; for (const [ fieldKey, condition ] of Object.entries(whereInput)) { normalized[fieldKey] = this.normalizeWhereCondition(fieldKey, condition); } return normalized; } extractWhereValues(normalizedWhere = {}) { if (!this.isPlainObject(normalizedWhere)) { return {}; } const whereValues = {}; for (const [ fieldKey, condition ] of Object.entries(normalizedWhere)) { if (this.isPlainObject(condition) && Object.prototype.hasOwnProperty.call(condition, 'value')) { whereValues[fieldKey] = condition.value; } else { whereValues[fieldKey] = condition; } } return whereValues; } prepareWhereContext(data = {}, options = {}) { const specialFieldMap = this.isPlainObject(options.specialFieldMap) ? options.specialFieldMap : {}; const rawWhere = this.isPlainObject(data && data.where) ? data.where : {}; const normalizedWhere = this.normalizeWhereParams(rawWhere); const parsed = parseWhereConditions({ where: normalizedWhere, app: this.app, specialFieldMap, }); if (!parsed.ok) { throw new Error(`where 参数解析失败: ${parsed.reason}`); } const whereValues = this.extractWhereValues(normalizedWhere); this.ctx.whereRaw = rawWhere; this.ctx.where = normalizedWhere; this.ctx.whereValue = whereValues; this.ctx.whereParsed = parsed.result; if (this.isPlainObject(data)) { data.where = normalizedWhere; } return { where: normalizedWhere, whereValue: whereValues, parsed: parsed.result, }; } async findQimenAppWithContract(appkey, customerId, warehouseCode) { const { app } = this; const cacheKey = `contract:${appkey}:${customerId}:${warehouseCode}`; try { let cacheResult = null; try { cacheResult = await Promise.race([ this.app.getCacheAsync(cacheKey), new Promise(resolve => setTimeout(() => { app.logger.warn('[RedisTimeout] Redis get operation timeout'); resolve(null); }, 100)), ]); } catch (cacheError) { app.logger.warn('[RedisGetError]', cacheError.message); // Redis 错误时继续数据库查询 } if (cacheResult) { try { const parsedResult = cacheResult; if (parsedResult) { app.logger.info('[CacheHit] Found in cache', cacheKey); return parsedResult; } } catch (parseError) { app.logger.error('[RedisParseError]', parseError.message, cacheKey); } } // 3. 数据库查询 app.logger.info('[CacheMiss] Querying from database', { appkey, customerId, warehouseCode }); const dbResult = await this.queryFromDatabase(appkey, customerId, warehouseCode); // 4. 异步设置缓存(添加安全检查) this.app.setCacheAsync(cacheKey, dbResult).catch(error => { app.logger.error('[AsyncCacheError]', error.message); }); return dbResult; } catch (error) { app.logger.error('[findQimenAppWithContract] Query failed', error.message, { appkey, customerId, warehouseCode }); throw error; } } // 提取数据库查询逻辑 async queryFromDatabase(appkey, customerId, warehouseCode) { const { app } = this; // 检查模型是否存在 if (!app.model || !app.model.ApiApp) { throw new Error('ApiApp model is not available'); } return await app.model.ApiApp.findOne({ attributes: [ 'id', 'app_name', 'qimen_app_key', 'qimen_customer_id', 'qimen_warehouse_code', 'api_version', 'sign_method', 'rate_limit', 'timeout_seconds', [ app.Sequelize.col('contract.store_id'), 'store_id' ], [ app.Sequelize.col('contract.warehouse_id'), 'warehouse_id' ], [ app.Sequelize.col('contract.auth_end'), 'contract_auth_end' ], [ app.Sequelize.col('contract.auth_status'), 'contract_auth_status' ], [ app.Sequelize.col('contract.apply_reason'), 'apply_reason' ], [ app.Sequelize.col('contract.review_comment'), 'review_comment' ], [ app.Sequelize.col('contract.warehouse.status'), 'warehouse_status' ], [ app.Sequelize.col('contract.warehouse.auth_end'), 'warehouse_auth_end' ], ], where: { qimen_app_key: appkey, qimen_customer_id: customerId, qimen_warehouse_code: warehouseCode, is_enabled: 1, }, include: [ { model: app.model.StoreWarehouse, as: 'contract', attributes: [], required: false, include: [ { model: app.model.Store, as: 'warehouse', attributes: [], required: false, }, ], }, ], raw: true, timeout: 10000, // 10秒超时 }); } async checkAuth(servicePath, actionName, authHeader) { const { ctx, app } = this; // 配置免登录和免鉴权的接口 const _noNeedLogin = (this._noNeedLogin || '').split(','); const _noNeedRight = (this._noNeedRight || '').split(','); const _noNeedAuth = (this._noNeedAuth || '').split(','); const _noNeedLog = (this._noNeedLog || '').split(','); const api_path = `${servicePath}.${actionName}`; const result = { status: 401, message: '', user: null, isLog: true, }; if (_noNeedLog.indexOf('*') > -1 || _noNeedLog.indexOf(actionName) > -1) { result.isLog = false; } // 1. 检查是否在免登录列表 if (_noNeedLogin.indexOf('*') > -1 || _noNeedLogin.indexOf(actionName) > -1) { result.status = 200; result.message = 'ok'; return result; } // 2. 检查是否有认证令牌 if (!authHeader || !authHeader.startsWith('Bearer ')) { result.status = 401; result.message = '未提供有效的认证令牌'; return result; } const token = authHeader.substring(7); try { // 3. 验证JWT令牌 const decoded = app.jwt.verify(token, app.config.jwt.secret); const now = Math.floor(Date.now() / 1000); const expiresIn = decoded.exp - now; const renewThreshold = app.config.jwt.renewThreshold ?? (app.config.jwt.expiresIn ? app.config.jwt.expiresIn - 1 : 14399); if (expiresIn < renewThreshold && expiresIn > 0) { // 移除过期时间(exp)和签发时间(iat),保留其他payload const payload = { ...decoded }; delete payload.exp; delete payload.iat; // 生成新的 token,使用原来的有效时间配置 const newToken = app.jwt.sign( payload, app.config.jwt.secret, { expiresIn: app.config.jwt.expiresIn || '3600', } ); // 设置新的 token 到响应头 ctx.set('Authorization', `Bearer ${newToken}`); } // 4. 获取用户信息 const user = await ctx.service.systems.auth.user.findById(decoded.id || decoded.userId); if (!user) { result.status = 401; result.message = '用户不存在或已被删除'; return result; } if (user.status !== 1) { result.status = 403; result.message = '账号已被禁用'; return result; } if (!(_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1)) { if (user.auth_end && new Date(user.auth_end) < new Date()) { result.status = 406; result.message = '仓库有效期已过期'; return result; } } // 5. 检查是否在免权限列表 if (_noNeedRight.indexOf('*') > -1 || _noNeedRight.indexOf(actionName) > -1) { // 免权限验证,只验证登录状态 this.setUserContext(ctx, user, decoded); result.status = 200; result.message = 'ok'; result.user = user; return result; } // 6. 验证API权限(只检查类型为api的权限) const hasPermission = await this.checkApiPermission(user, api_path); if (!hasPermission) { result.status = 403; result.message = '无权访问该接口'; return result; } // 7. 验证通过,设置用户上下文 this.setUserContext(ctx, user, decoded); result.status = 200; result.message = 'ok'; result.user = user; return result; } catch (error) { console.error('鉴权错误:', error); if (error.name === 'TokenExpiredError') { result.status = 401; result.message = '令牌已过期'; } else if (error.name === 'JsonWebTokenError') { result.status = 401; result.message = '无效的令牌'; } else if (error.name === 'SequelizeDatabaseError') { result.status = 500; result.message = '数据库错误'; } else { result.status = 500; result.message = '服务器内部错误'; } return result; } } /** * 检查用户是否有API访问权限(只检查类型为api的权限) * @param {Object} user - 用户信息 * @param {string} apiPath - API路径 * @return {Promise} 是否有权限 */ async checkApiPermission(user, apiPath) { const normalizedApiPath = String(apiPath || '').trim().toLowerCase(); if (!normalizedApiPath) { return false; } try { const { allAccess, pathSet, permissionIds } = this.extractApiPermissionState(user); if (allAccess) { return true; } if (pathSet.has(normalizedApiPath)) { return true; } if (permissionIds.size > 0 && this.ctx.model && this.ctx.model.Permission && typeof this.ctx.model.Permission.findAll === 'function') { const permissionRows = await this.ctx.model.Permission.findAll({ where: { id: [ ...permissionIds ], status: 1, }, attributes: [ 'id', 'path' ], raw: true, }); return permissionRows.some(item => String(item && item.path || '').trim().toLowerCase() === normalizedApiPath); } return false; } catch (error) { console.error('检查API权限失败:', error); return false; } } extractApiPermissionState(user = {}) { const state = { allAccess: false, pathSet: new Set(), permissionIds: new Set(), }; const visited = new Set(); const sources = [ user.permissions, user.role_permissions, user.permission_ids, user.permissionIds, ]; for (const source of sources) { this.collectApiPermissionValue(source, state, visited); if (state.allAccess) { break; } } return state; } collectApiPermissionValue(value, state, visited) { if (state.allAccess || value === undefined || value === null) { return; } if (typeof value === 'string') { const trimmed = value.trim(); if (!trimmed) { return; } if (trimmed === '*') { state.allAccess = true; return; } if ((trimmed.startsWith('[') && trimmed.endsWith(']')) || (trimmed.startsWith('{') && trimmed.endsWith('}'))) { try { const parsed = JSON.parse(trimmed); if (parsed !== value) { this.collectApiPermissionValue(parsed, state, visited); return; } } catch (_) { // 忽略 JSON 解析失败,继续按普通字符串处理。 } } if (trimmed.includes(',')) { this.collectApiPermissionValue(trimmed.split(','), state, visited); return; } const asNumber = Number(trimmed); if (Number.isInteger(asNumber) && String(asNumber) === trimmed) { state.permissionIds.add(asNumber); return; } state.pathSet.add(trimmed.toLowerCase()); return; } if (typeof value === 'number') { if (Number.isInteger(value) && value > 0) { state.permissionIds.add(value); } return; } if (Array.isArray(value)) { for (const item of value) { this.collectApiPermissionValue(item, state, visited); if (state.allAccess) { break; } } return; } if (typeof value !== 'object') { return; } if (visited.has(value)) { return; } visited.add(value); if (value.allAccess === true || value.isAllAccess === true) { state.allAccess = true; return; } const candidates = [ value.path, value.apiPath, value.permission, value.permissionPath, value.value, value.id, value.permission_id, value.permissionId, value.permissions, value.permission_ids, value.permissionIds, value.children, value.items, value.list, ]; for (const candidate of candidates) { this.collectApiPermissionValue(candidate, state, visited); if (state.allAccess) { break; } } } /** * 设置用户上下文信息 * @param {Object} ctx - 上下文对象 * @param {Object} user - 用户信息 * @param {Object} decoded - JWT解码信息 */ setUserContext(ctx, user, decoded) { // 设置用户基本信息 ctx.user = user; ctx.userId = user.id; ctx.username = user.username; ctx.realName = user.real_name; if (user.store_id) { ctx.currentStoreId = user.store_id; } // 设置平台信息 if (decoded.platform_code) { ctx.platformCode = decoded.platform_code; } // 设置JWT原始信息 ctx.jwtPayload = decoded; } systemInit(_noNeedLogin, _noNeedRight, _noNeedLog = '*', _noNeedAuth = '*') { this._noNeedLogin = _noNeedLogin; this._noNeedRight = _noNeedRight; this._noNeedLog = _noNeedLog; this._noNeedAuth = _noNeedAuth; } } module.exports = MainService;