import * as path from "path";
|
import * as fs from "fs";
|
import { LoginInfo } from "../entity/sys/loginInfo";
|
import { SysUserLog } from "../entity/sys/core/sysUserLog";
|
import { getManager, getRepository } from "typeorm";
|
const crypto = require("crypto");
|
import { IHelper } from "egg";
|
import * as nodemailer from "nodemailer";
|
import { isObject } from "util";
|
import { PlatUserProduct } from "../entity/sys/plat/platUserProduct";
|
import moment = require("moment");
|
|
module.exports = {
|
/**
|
* 创建多级目录
|
*/
|
mkdir(pathToCreate) {
|
pathToCreate.split(path.sep).reduce((currentPath, folder) => {
|
currentPath += folder + path.sep;
|
if (!fs.existsSync(currentPath)) {
|
fs.mkdirSync(currentPath);
|
}
|
return currentPath;
|
}, "");
|
},
|
/**
|
* 删除指定目录及内部的文件和文件夹
|
* @param _path 需要删除的目录
|
* @param beforeDays 删除N天前的文件
|
*/
|
deldir(_path, beforeDays: number = 0) {
|
let startDate = moment(Date.now());
|
let files = [];
|
if (fs.existsSync(_path)) {
|
files = fs.readdirSync(_path);
|
files.forEach(file => {
|
let curPath = _path + path.sep + file;
|
let stat = fs.statSync(curPath);
|
let days = moment(startDate).diff(stat.ctime, "days");
|
if (beforeDays !== 0 && days < beforeDays) {
|
return true;
|
}
|
if (stat.isDirectory()) {
|
this.deldir(curPath); //递归删除文件夹
|
} else {
|
fs.unlinkSync(curPath); //删除文件
|
}
|
});
|
files = fs.readdirSync(_path);
|
if (files.length == 0) {
|
fs.rmdirSync(_path);
|
}
|
}
|
},
|
|
/**
|
* 获得用户信息
|
*/
|
async userInfo(this: IHelper): Promise<LoginInfo> {
|
const { ctx } = this;
|
let apitype = ctx.header.apitype;
|
let redis = ctx.app.redis.clients.get("userInfo");
|
|
// 通用用户
|
const getInfo = async () => {
|
let guid = ctx.request.get("guid");
|
let accessTokenKey = "AccessToken_" + guid;
|
let signTokenKey = "Token_" + guid;
|
if (!guid) {
|
return null;
|
}
|
|
let _userInfo: any;
|
if (redis) {
|
_userInfo = await redis.get(accessTokenKey);
|
if (_userInfo) {
|
try {
|
_userInfo = JSON.parse(_userInfo);
|
} catch (error) {
|
_userInfo = null;
|
}
|
}
|
}
|
|
//如果缓存没有,在去访问日志里获取
|
if (!_userInfo && guid) {
|
let logInfo = await getRepository(SysUserLog).findOne({
|
select: ["loginInfo", "signTokenInfo"],
|
where: {
|
guid: guid
|
}
|
});
|
if (logInfo && logInfo.loginInfo) {
|
_userInfo = JSON.parse(logInfo.loginInfo) as LoginInfo;
|
redis && redis.set(accessTokenKey, JSON.stringify(_userInfo));
|
}
|
|
if (logInfo && logInfo.signTokenInfo) {
|
redis && redis.set(signTokenKey, logInfo.signTokenInfo);
|
}
|
}
|
if (_userInfo != null) {
|
_userInfo = this.objectToCase(_userInfo) as LoginInfo;
|
}
|
return _userInfo;
|
};
|
|
// 对外账套客户端用户
|
const getInfo_client = async () => {
|
let appKey = ctx.header.appkey;
|
let appSecret = ctx.header.appsecret;
|
let signTokenKey = "clientToken_" + appSecret;
|
if (!appSecret) {
|
return null;
|
}
|
|
var _userInfo = redis && (await redis.get(signTokenKey));
|
if (!_userInfo) {
|
_userInfo = await this.dbRead.findOne(PlatUserProduct, {
|
where: {
|
appKey: appKey,
|
appSecret: appSecret
|
}
|
});
|
if (_userInfo) {
|
redis && (await redis.set(signTokenKey, JSON.stringify(_userInfo), "EX", 7 * 24 * 60 * 60));
|
}
|
} else {
|
_userInfo = JSON.parse(_userInfo);
|
}
|
_userInfo.userType = apitype;
|
return _userInfo;
|
};
|
|
let userInfo = new LoginInfo();
|
if (apitype === "client") {
|
userInfo = await getInfo_client();
|
} else {
|
userInfo = await getInfo();
|
}
|
if (!userInfo) {
|
userInfo = new LoginInfo();
|
userInfo.userProduct_Id = 1007;
|
userInfo.user_Id = 1;
|
userInfo.userTrueName = "系统";
|
}
|
userInfo.consignor_Id = 30;
|
userInfo.consignorCode = "GX30";
|
userInfo.consignorName = "广州西门子";
|
|
return userInfo;
|
},
|
|
/**
|
* 是否SaaS用户
|
*/
|
async isSaaS(this: IHelper): Promise<Boolean> {
|
let _userInfo = await this.userInfo();
|
let _isSaaS = ["user", "consignor"].indexOf(_userInfo.userType) >= 0;
|
|
return _isSaaS;
|
},
|
|
/**
|
* MD5加密
|
* @param password 需要加密的明文
|
*/
|
md5EncodingSalt(password) {
|
const md5 = crypto.createHash("md5");
|
return md5.update(password + "{MINGpin365}").digest("hex");
|
},
|
/**
|
* 生成签名
|
* @param headerParams 签名前字符串
|
* @param params 传递数据参数
|
*/
|
getSignature: function (headerParams, params): string | undefined {
|
try {
|
if (typeof params === "string") {
|
params = JSON.parse(params);
|
}
|
} catch (e) {
|
console.log("传递数据不是有效的JSON数据");
|
return undefined;
|
}
|
// 去掉JSON数据的空格
|
var data = params && params.noDataSign ? "" : JSON.stringify(params);
|
// console.log("json=" + data);
|
|
let _signStr = headerParams + data;
|
// console.log("排序前:", _signStr);
|
let signStr = _signStr.split("").sort(function (a, b) {
|
var v = a > b ? 1 : -1;
|
return v;
|
});
|
_signStr = signStr.join("");
|
// console.log("排序后:", _signStr);
|
const md5 = crypto.createHash("md5");
|
let signResult: string = md5.update(_signStr).digest("hex");
|
|
return signResult.toUpperCase();
|
},
|
/**
|
* MD5加密
|
* @param 需要MD5加密字符串
|
*/
|
md5: function (data: string): string {
|
const md5 = crypto.createHash("md5");
|
let signResult: string = md5.update(data).digest("hex");
|
|
return signResult.toUpperCase();
|
},
|
|
/**
|
* 获得SaaS账套权限
|
*/
|
async getSaaSAuthList(this: IHelper): Promise<Array<any> | undefined> {
|
const { ctx, app } = this;
|
let userRedis = app.redis.clients.get("userInfo");
|
let saaSAuthList: Array<any> | undefined;
|
let guid = ctx.get("guid");
|
let accessTokenKey = "SaaSAuth_" + guid;
|
if (guid && userRedis) {
|
let saaSAuth = await userRedis.get(accessTokenKey);
|
if (saaSAuth) saaSAuthList = JSON.parse(saaSAuth);
|
}
|
//如果缓存没有,在去访问日志里获取
|
if (!saaSAuthList && guid) {
|
let logInfo = await getManager()
|
.getRepository(SysUserLog)
|
.findOne({
|
select: ["saaSAuth"],
|
where: {
|
gUID: guid
|
},
|
order: { log_Id: "DESC" }
|
});
|
if (logInfo && logInfo.saaSAuth) {
|
saaSAuthList = JSON.parse(logInfo.saaSAuth);
|
userRedis && (await userRedis.set(accessTokenKey, logInfo.saaSAuth));
|
}
|
}
|
|
return saaSAuthList;
|
},
|
/**
|
* 将头字母转为大小写,驼峰命名规则,默认转为小
|
* @param {String} str 需要转换的字符串
|
* @param {String} type 转换类型,Upper或者Lower
|
*/
|
caseStyle(str: string, type = "Lower") {
|
if (!str || str.length < 2) return str;
|
if (type === "Upper") {
|
str = str.charAt(0).toUpperCase() + str.slice(1);
|
} else {
|
str = str.replace("TMS", "tms");
|
str = str.replace("CRM", "crm");
|
str = str.replace("OA", "oa");
|
str = str.replace("ERP", "erp");
|
str = str.charAt(0).toLowerCase() + str.slice(1);
|
}
|
return str;
|
},
|
/**
|
* 将对象属性首字母转为大小写,默认转换为小写
|
* @param {Object} obj 需要转换的对象
|
* @param {String} type 转换类型,Upper或者Lower
|
*/
|
objectToCase(obj, type = "Lower") {
|
if (!obj) return obj;
|
|
var data = {};
|
// 数据转换
|
Object.keys(obj).forEach(key => {
|
let val = obj[key];
|
let _key = this.caseStyle(key, type);
|
if (Array.isArray(val)) {
|
data[_key] = this.arrayToCase(val);
|
} else if (isObject(val)) {
|
data[_key] = this.objectToCase(val);
|
} else {
|
data[_key] = val;
|
}
|
});
|
return data;
|
},
|
/**
|
* 将数组属性首字母转为大小写,默认转换为小写
|
* @param {Array} obj 需要转换的数组
|
* @param {String} type 转换类型,Upper或者Lower
|
*/
|
arrayToCase(obj, type = "Lower") {
|
if (!obj) return obj;
|
|
if (!Array.isArray(obj)) {
|
return obj;
|
}
|
|
let _arrList: Array<any> = [];
|
for (let item of obj) {
|
item = this.objectToCase(item, type);
|
_arrList.push(item);
|
}
|
return _arrList;
|
},
|
/**
|
* 发送邮件
|
* @param {String} recipient 收件人
|
* @param {String} subject 发送的主题
|
* @param {String} html 发送的html内容
|
*/
|
async sendMail(this: IHelper, recipient, subject, html): Promise<any> {
|
let { ctx } = this;
|
const config = {
|
host: await ctx.service.common.getConfig("emailHost"),
|
user: await ctx.service.common.getConfig("emailUser"),
|
pass: await ctx.service.common.getConfig("emailPass")
|
};
|
let smtpTransport = nodemailer.createTransport({
|
host: config.host,
|
port: 465,
|
secure: false, // true for 465, false for other ports
|
auth: {
|
user: config.user,
|
pass: config.pass
|
}
|
});
|
let result = await smtpTransport.sendMail({
|
from: config.user,
|
to: recipient,
|
subject: subject,
|
html: html
|
});
|
result;
|
},
|
/**
|
* 进程暂停
|
* @param time 暂停时间,单位毫秒
|
*/
|
async sleep(time) {
|
var promise = new Promise(resolve => {
|
setTimeout(() => {
|
resolve();
|
}, time);
|
});
|
return promise;
|
},
|
/**
|
* 将SQL语句敏感词过滤掉
|
* @param 需要过滤的SQL语句
|
*/
|
sqlSecurity(sql) {
|
if (sql) {
|
sql = sql.replace(/select|delete|update|from|where|'|"|;/gi, "");
|
}
|
return sql;
|
},
|
/**
|
* 深度复制对象
|
* @param 需要复制的原对象
|
*/
|
copyObject(obj) {
|
return JSON.parse(JSON.stringify(obj));
|
}
|
};
|