381 lines
11 KiB
JavaScript
381 lines
11 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
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) {
|
||
console.log('fail', message, data);
|
||
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,
|
||
};
|
||
}
|
||
|
||
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}`;
|
||
console.log(api_path, '_noNeedLog', _noNeedLog);
|
||
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 NewauthHeader = '';
|
||
const decoded = app.jwt.verify(token, app.config.jwt.secret);
|
||
const now = Math.floor(Date.now() / 1000);
|
||
const expiresIn = decoded.exp - now;
|
||
if (expiresIn < 1800 && expiresIn > 0) {
|
||
// 移除过期时间(exp)和签发时间(iat),保留其他payload
|
||
const { exp, iat, ...payload } = decoded;
|
||
|
||
// 生成新的 token,使用原来的有效时间配置
|
||
const newToken = app.jwt.sign(
|
||
payload,
|
||
app.config.jwt.secret,
|
||
{
|
||
expiresIn: app.config.jwt.expiresIn || '3600',
|
||
}
|
||
);
|
||
|
||
// 设置新的 token 到响应头
|
||
ctx.set('Authorization', `Bearer ${newToken}`);
|
||
console.log('Token 已刷新,新 token:', newToken.substring(0, 50) + '...');
|
||
}
|
||
// 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) {
|
||
} else {
|
||
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的权限)
|
||
console.log('检查权限开始');
|
||
|
||
const hasPermission = await this.checkApiPermission(user, api_path);
|
||
console.log('检查权限结束', hasPermission);
|
||
|
||
|
||
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<boolean>}
|
||
*/
|
||
async checkApiPermission(user, apiPath) {
|
||
const { ctx } = this;
|
||
|
||
console.log(user);
|
||
try {
|
||
// 方法1: 从用户的权限列表中检查(如果已经加载了权限)
|
||
if (user.permissions && Array.isArray(user.permissions)) {
|
||
// 用户权限列表中可能包含所有权限,需要过滤出api权限
|
||
console.log('user.permissions', user.permissions);
|
||
return user.permissions.includes(apiPath);
|
||
}
|
||
return false;
|
||
} catch (error) {
|
||
console.error('检查API权限失败:', error);
|
||
return false;
|
||
}
|
||
}
|
||
/**
|
||
* 设置用户上下文信息
|
||
* @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;
|