abler-api 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1191 @@
1
+ import require$$0 from 'crypto';
2
+ import require$$1 from 'abler-util';
3
+ import require$$2 from 'abler-db';
4
+
5
+ const crypto = require$$0;
6
+ const ppUtil$1 = require$$1.ppUtil;
7
+ const {
8
+ dbUtil,
9
+ kvStorage
10
+ } = require$$2;
11
+ let conf, appSetting, err, dbSql;
12
+ const pnToken = "access_token",
13
+ hnToken = pnToken,
14
+ pnApiKey = "apiKey",
15
+ hnApiKey = pnApiKey.toLowerCase(),
16
+ // 我们接收到的 headers 中的字段名总是全小写的
17
+ pnApiSecret = "apiSecret",
18
+ hnApiSecret = pnApiSecret.toLowerCase();
19
+ const MD5 = ppUtil$1.MD5,
20
+ moveProperty = ppUtil$1.moveProperty,
21
+ commonUtils = ppUtil$1;
22
+
23
+ class apiUtil$1 {
24
+ static debugFlag = pputil.newGuid(); //应用必须设置,否则谁也不知道是啥
25
+
26
+ static testFlag = pputil.newGuid();
27
+ static envId_dev = "?"; // static apiCallRecSaver;
28
+
29
+ static config(appConfig, appErrCfg, appDbSql) {
30
+ ppUtil$1.config(appConfig, appErrCfg);
31
+ conf = appConfig;
32
+ appSetting = conf?.appSetting;
33
+ err = appErrCfg, dbSql = appDbSql;
34
+ apiUtil$1.debugFlag = appSetting?.debugFlag || apiUtil$1.debugFlag;
35
+ apiUtil$1.testFlag = appSetting?.testFlag || apiUtil$1.testFlag; // apiUtil.apiCallRecSaver = apiCallRecSaver;
36
+ } //#region ===== 需要应用系统重写的方法
37
+
38
+ /**
39
+ * 根据机构标识获取机构的 ApiSecret
40
+ * @param companyId
41
+ * @returns {*}
42
+ */
43
+
44
+
45
+ static _getApiSecret(companyId) {
46
+ return ppUtil$1.newGuid();
47
+ }
48
+ /**
49
+ * 保存 API 调用记录,应用系统必须重写此方法
50
+ * @param rec
51
+ * @param responseData
52
+ * @returns {Promise<unknown>}
53
+ */
54
+
55
+
56
+ static async _saveApiCallRec(rec, responseData) {
57
+ return false;
58
+ }
59
+ /**
60
+ * 检查API调用签名是否已经完成了验证
61
+ * @param req
62
+ */
63
+
64
+
65
+ static signatureVerified(req) {
66
+ return req.signatureVerified;
67
+ } //#endregion
68
+ //#region ===== API服务相关工具
69
+
70
+ /**
71
+ * 获取客户端IP地址
72
+ * @param req
73
+ * @returns {*|string|string}
74
+ */
75
+
76
+
77
+ static getClientIp(req) {
78
+ let ip = req.headers["x-real-ip"] || req.headers["x-true-ip"] || req.headers['x-forwarded-for'] || req.headers['x-forward-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.headers['host'] || ""; // console.log("Request IP:", ip, "req: ", req);
79
+
80
+ if (ip.indexOf(",") >= 0) {
81
+ ip = ip.split(',')[0];
82
+ }
83
+
84
+ if (ip.indexOf(":") >= 0) {
85
+ ip = ip.substring(ip.lastIndexOf(':') + 1);
86
+ }
87
+
88
+ return ip;
89
+ }
90
+ /**
91
+ * 从请求中解出数据,包括路径参数、查询参数和Body
92
+ * @param req
93
+ * @returns {*}
94
+ */
95
+
96
+
97
+ static extractParams(req) {
98
+ if (!req._requestParams) {
99
+ if (req.method === "POST" || req.method === "PUT") {
100
+ let contentType = req.headers["content-type"] || "application/json";
101
+
102
+ if (contentType.startsWith("multipart/form-data")) {
103
+ req._requestParams = new Object();
104
+
105
+ for (let k in req.body) {
106
+ req._requestParams[k] = req.body[k];
107
+ }
108
+ } else {
109
+ req._requestParams = req.body;
110
+ }
111
+ } else {
112
+ req._requestParams = req.query;
113
+ }
114
+
115
+ if (req.headers["content-type"] !== "application/json") {
116
+ const obj = req._requestParams;
117
+
118
+ for (let key in obj) {
119
+ if (!obj.hasOwnProperty(key)) continue;
120
+ let value = obj[key];
121
+
122
+ if (typeof value === "string" && value.length > 0) {
123
+ if (value[0] === "{" || value[0] === "[") {
124
+ try {
125
+ obj[key] = JSON.parse(value);
126
+ continue;
127
+ } catch (e) {}
128
+ }
129
+
130
+ let x = JSON.hbDateConv(key, value);
131
+
132
+ if (x !== value) {
133
+ obj[key] = x;
134
+ }
135
+ }
136
+ }
137
+ }
138
+
139
+ if (req.params) {
140
+ req._requestParams = Object.assign(req.params, req._requestParams);
141
+ }
142
+
143
+ apiUtil$1.setParamsFunctions(req._requestParams);
144
+ }
145
+
146
+ return req._requestParams;
147
+ }
148
+
149
+ static extractTokenData(req) {
150
+ if (req.tokenData) {
151
+ return req.tokenData;
152
+ }
153
+
154
+ let params = apiUtil$1.extractParams(req);
155
+ let tokenData = {
156
+ apiKey: req.headers[hnApiKey] || params[pnApiKey],
157
+ apiSecret: req.headers[hnApiSecret] || params[pnApiSecret],
158
+ clientIp: apiUtil$1.getClientIp(req)
159
+ };
160
+ return tokenData;
161
+ }
162
+ /**
163
+ * 为从传入请求中解出的参数对象设置一些函数属性,包括 asNumber, asBool
164
+ * @param params
165
+ */
166
+
167
+
168
+ static setParamsFunctions(params) {
169
+ ppUtil$1.defUnenumProp(params, "asNumber", function (name, minValue, maxValue, defaultValue) {
170
+ // if (!this.hasOwnProperty(name)) // {} 定义的对象没有 hasOwnProperty 函数
171
+ if (this[name] === undefined) return defaultValue;
172
+ let result = +this[name];
173
+
174
+ if (typeof result !== "number" || result < minValue || result > maxValue) {
175
+ throw [err.INVALID_PARAM, `参数 ${name} 必须是 ${minValue} ~ ${maxValue} 之间的数字`];
176
+ }
177
+
178
+ return result;
179
+ });
180
+ ppUtil$1.defUnenumProp(params, "asBool", function (name, defaultValue) {
181
+ if (this[name] === undefined) return defaultValue;
182
+ let result = JSON.parse(this[name]);
183
+ return !!result;
184
+ });
185
+ }
186
+ /**
187
+ * 将返回结果转向到指定地址或者通过response发送返回结果
188
+ * @param res
189
+ * @param redirectUrl
190
+ * @param data
191
+ */
192
+
193
+
194
+ static sendOrRedirect(res, redirectUrl, data) {
195
+ if (redirectUrl) {
196
+ redirectUrl = urlAppendParams(redirectUrl, data, true);
197
+ res.redirect(redirectUrl);
198
+ } else {
199
+ res.send(data);
200
+ }
201
+ }
202
+ /**
203
+ * 生成 API 成功返回结果
204
+ * @param data
205
+ * @param req
206
+ * @returns {{datetime: Date, success: boolean, stateCode: number, message: string}}
207
+ */
208
+
209
+
210
+ static apiSuccess(data, req) {
211
+ let response = {
212
+ success: true,
213
+ stateCode: 0,
214
+ message: '',
215
+ datetime: new Date()
216
+ };
217
+
218
+ if (req && req.headers) {
219
+ let userAgent = req.headers["user-agent"];
220
+
221
+ if (userAgent && userAgent.startsWith("Postman")) {
222
+ response._elapse = (new Date().valueOf() - req.headers.timestamp) / 1000;
223
+ }
224
+ }
225
+
226
+ if (data && data._message_) {
227
+ response.message = data._message_;
228
+ delete data._message_;
229
+ }
230
+
231
+ response.data = data;
232
+ if (Array.isArray(data) && typeof data.recordCount != 'undefined') response.recordCount = data.recordCount;
233
+ return response;
234
+ }
235
+ /**
236
+ * 生成 API 失败返回结果
237
+ * @param error
238
+ * @param req
239
+ * @returns {*}
240
+ */
241
+
242
+
243
+ static apiFail(error, req) {
244
+ configNeeded();
245
+ let response = err.ERROR(error, err.errorLangParamFlag + ppUtil$1.getMsgLang(req));
246
+ response.datetime = new Date();
247
+
248
+ if (req && req.headers) {
249
+ let userAgent = req.headers["user-agent"];
250
+
251
+ if (userAgent && userAgent.startsWith("Postman")) {
252
+ response._elapse = (new Date().valueOf() - req.headers.timestamp) / 1000;
253
+ }
254
+ }
255
+
256
+ return response;
257
+ }
258
+ /**
259
+ * 生成面向服务商的API成功返回结果
260
+ * @param data
261
+ * @param req
262
+ * @returns {*}
263
+ */
264
+
265
+
266
+ static spoApiSucc(data, req) {
267
+ let params = apiUtil$1.extractParams(req);
268
+ return apiUtil$1.apiSuccess(data, req, params.spOrderNum);
269
+ }
270
+ /**
271
+ * 生成面向服务商的API失败返回结果
272
+ * @param error
273
+ * @param req
274
+ * @returns {*}
275
+ */
276
+
277
+
278
+ static spoApiFail(error, req) {
279
+ let params = apiUtil$1.extractParams(req);
280
+ return apiUtil$1.apiFail(error, req, params.spOrderNum);
281
+ }
282
+ /**
283
+ * API 服务结束,发送响应
284
+ * @param response
285
+ * @param promise
286
+ */
287
+
288
+
289
+ static async responseOf(response, promise) {
290
+ promise.then(function (data) {
291
+ // console.log('RES:', apiSuccess(data));
292
+ if (!response.finished) response.send(apiUtil$1.apiSuccess(data, response.req));
293
+ }, function (error) {
294
+ console.log('ERROR:', error);
295
+ if (!response.finished) response.send(apiUtil$1.apiFail(error, response.req));
296
+ });
297
+ }
298
+ /**
299
+ * 面向服务商的API结束,发送响应
300
+ * @param response
301
+ * @param promise
302
+ */
303
+
304
+
305
+ static async spoApiResponse(response, promise) {
306
+ promise.then(function (result) {
307
+ let responseData = apiUtil$1.spoApiSucc(result, response.req);
308
+
309
+ apiUtil$1._saveApiCallRec(response.req.apiCallRec, responseData);
310
+
311
+ if (!response.finished) response.send(responseData);
312
+ }, function (error) {
313
+ console.log('ERROR:', error);
314
+ let responseData = apiUtil$1.spoApiFail(error, response.req);
315
+
316
+ apiUtil$1._saveApiCallRec(response.req.apiCallRec, responseData);
317
+
318
+ if (!response.finished) response.send(responseData);
319
+ });
320
+ }
321
+ /**
322
+ * 从请求参数中获取查询参数
323
+ * @param req
324
+ * @param res
325
+ * @returns {*}
326
+ */
327
+
328
+
329
+ static getQueryOptions(req, res) {
330
+ req.headers.timestamp = new Date().valueOf(); // let options = {replacements: {}};
331
+
332
+ let options = {};
333
+ let parameters = apiUtil$1.extractParams(req);
334
+
335
+ for (let qryParam in parameters) {
336
+ if (qryParam !== 'token') {
337
+ if (['start', 'limit', 'orderby', 'orderBy'].indexOf(qryParam) >= 0) {
338
+ options[qryParam] = parameters[qryParam];
339
+ delete parameters[qryParam];
340
+ } // else
341
+ // options.replacements[qryParam] = parameters[qryParam];
342
+
343
+ }
344
+ }
345
+
346
+ if (options.limit && !options.start) {
347
+ options.start = 0;
348
+ }
349
+
350
+ if (options.orderby) {
351
+ options.orderBy = options.orderby;
352
+ } // options.__debug__ = req.headers['__debug__'] && req.headers['__debug__'] == "true";
353
+
354
+
355
+ options.replacements = parameters; // if (arguments.length > 1) //其后的每个参数是要求必须存在的参数名称
356
+ // {
357
+ // for(i=1; i<arguments.length; i++){
358
+ // var paramName = arguments[i];
359
+ // if (!qryOptions.replacements[paramName])
360
+ // error();
361
+ // }
362
+ // }
363
+
364
+ options.userInfo = req.userInfo;
365
+ return apiUtil$1.setOptionsPropFuncions(options, res);
366
+ }
367
+ /**
368
+ * 为API请求 options 设置属性
369
+ * @param options
370
+ * @param res
371
+ * @returns {{identifyLimit}|*}
372
+ */
373
+
374
+
375
+ static setOptionsPropFuncions(options, res) {
376
+ // if (!options.identifyLimit) {
377
+ // // 根据企业标识获取身份认证限制相关设置,如果没有传递企业标识,
378
+ // // 则尝试从options.companyInfo或options.contractOrder中获取
379
+ // Object.defineProperty(options, "companyId", {
380
+ // get: function () {
381
+ // var result;
382
+ // if (this.companyInfo) {
383
+ // result = this.companyInfo.companyId;
384
+ // } else if (this.contractOrder) {
385
+ // result = this.contractOrder.companyId;
386
+ // } else if (this._companyId) {
387
+ // result = this._companyId;
388
+ // }
389
+ // return result;
390
+ // }
391
+ // });
392
+ // Object.defineProperty(options, "identifyLimit", {
393
+ // get: function () {
394
+ // if (!this._identifyLimit) {
395
+ // // this._identifyLimit = hb.waitPromise(_getIdentifyLimit(this.companyId));
396
+ // throw "options._identifyLimit 没有赋值";
397
+ // }
398
+ //
399
+ // return this._identifyLimit;
400
+ // },
401
+ // // configurable : true
402
+ // });
403
+ // }
404
+ if (res) {
405
+ Object.defineProperty(options, '_res', {
406
+ value: res,
407
+ enumerable: false
408
+ });
409
+ }
410
+
411
+ return options;
412
+ }
413
+ /**
414
+ * 从请求头获取token
415
+ * @param req
416
+ * @param res
417
+ * @param noErr
418
+ * @returns {Promise<*>}
419
+ */
420
+
421
+
422
+ static async extractToken(req, res, noErr) {
423
+ configNeeded();
424
+
425
+ if (!req.accessToken) {
426
+ //检查post的信息或者url查询参数或者头信息
427
+ let token = req.headers[hnToken] || req.headers['x-access-token']; //向后兼容
428
+
429
+ if (!token) {
430
+ let params = apiUtil$1.extractParams(req);
431
+ token = params[pnToken];
432
+
433
+ if (token) {
434
+ delete params[pnToken];
435
+ } else if (params.token) {
436
+ token = params.token; //向后兼容
437
+
438
+ delete params.token;
439
+ } else {
440
+ // 如果没有token,则返回错误
441
+ console.log(err.TOKEN_NEEDED);
442
+
443
+ if (res) {
444
+ res.send(err.ERROR(err.TOKEN_NEEDED));
445
+ } else if (!noErr) {
446
+ throw err.TOKEN_NEEDED;
447
+ }
448
+ }
449
+ }
450
+
451
+ req.accessToken = token;
452
+ }
453
+
454
+ return req.accessToken;
455
+ }
456
+ /**
457
+ * 检查是不是内部调用,应用系统可替换此函数实施更隐秘的检查
458
+ * @param req
459
+ * @returns {Promise<boolean|undefined>}
460
+ */
461
+
462
+
463
+ static async checkInternalToken(req) {
464
+ // return await checkInternalToken(req);
465
+ const params = apiUtil$1.extractParams(req);
466
+ req.accessToken = req.accessToken || apiUtil$1.extractToken(req);
467
+
468
+ if (req.accessToken === MD5(commonUtils.idNumDisturbing)) {
469
+ //todo: 检查IP
470
+ params.__internal__ = true;
471
+ req.ignoreToken = true; // if (params.idNum || params.personId) {
472
+ // return queryPersonUser(params.idNum, params.personId)
473
+ // .then(async userInfo => {
474
+ // if (!userInfo) {
475
+ // // console.log('queryPersonUser error.', e);
476
+ // throw err.TOKEN_INVALID;
477
+ // }
478
+ // if (req.tokenValidater) await req.tokenValidater(userInfo, req)
479
+ // req.userInfo = userInfo;
480
+ // return true
481
+ // })
482
+ // } else {
483
+ // return true
484
+ // }
485
+
486
+ return true;
487
+ } else {
488
+ // console.log('token error.', req.accessToken);
489
+ throw err.TOKEN_INVALID;
490
+ }
491
+ }
492
+ /**
493
+ * 检查请求是否存在合法的token,若不存在则抛出异常
494
+ * @param req
495
+ * @returns {Promise<void>}
496
+ */
497
+
498
+
499
+ static async checkRequestToken(req) {
500
+ req.accessToken = req.accessToken || apiUtil$1.extractToken(req);
501
+ await apiUtil$1.restoreTokenData(apiUtil$1.userTokenStoreKey(req.accessToken), apiUtil$1.tokenExpireTime(req)).then(async function (data) {
502
+ req.userInfo = apiUtil$1.setUserIdNo(data, data._idNo);
503
+ if (req.tokenValidater) await req.tokenValidater(req.userInfo, req);
504
+ return true;
505
+ }, async function (e) {
506
+ // 如果给定的token不存在,看看是不是平台内部调用
507
+ return await apiUtil$1.checkInternalToken(req);
508
+ });
509
+ }
510
+ /**
511
+ * 检查是不是调试模式
512
+ * @param req
513
+ * @returns {*|boolean|boolean}
514
+ */
515
+
516
+
517
+ static isDebugMode(req) {
518
+ if (req.__debug__ === undefined) {
519
+ let dbgToken = req.headers['__debug__'] || req.headers[apiUtil$1.debugFlag];
520
+
521
+ if (dbgToken) {
522
+ let envId = process.env.ECS_DEPLOY_ID;
523
+ req.__debug__ = dbgToken && dbgToken === MD5(req.headers.timestamp, commonUtils.commonHashDisturbing) && (envId === "florist_longdan" || envId === "shuzi");
524
+ } else {
525
+ req.__debug__ = false;
526
+ } // console.log("__debug__:", req.__debug__, "dbgToken:", dbgToken);
527
+
528
+ }
529
+
530
+ return req.__debug__; // return req.headers["postman-token"] || req.headers['__debug__'] && req.headers['__debug__'] == "true";
531
+ }
532
+ /**
533
+ * 检查是不是测试模式
534
+ * @param req
535
+ * @returns {*|boolean}
536
+ */
537
+
538
+
539
+ static isTestMode(req) {
540
+ if (req.__postman__ === undefined) {
541
+ let dbgToken = req.headers["__postman__"] || req.headers[apiUtil$1.testFlag];
542
+
543
+ if (dbgToken) {
544
+ let envId = process.env.ECS_DEPLOY_ID;
545
+ let testToken = MD5(req.headers.timestamp, apiUtil$1.extractToken(req, null, true) || req.headers.apikey);
546
+ req.__postman__ = dbgToken === testToken && (envId.indexOf("myfacesign.com") < 0 || envId.indexOf(".dev.") > 0);
547
+ } else {
548
+ req.__postman__ = false;
549
+ }
550
+ }
551
+
552
+ return req.__postman__;
553
+ }
554
+ /**
555
+ * 获取令牌过期时长
556
+ * @param req
557
+ * @returns {any}
558
+ */
559
+
560
+
561
+ static tokenExpireTime(req) {
562
+ return apiUtil$1.isDebugMode(req) ? 30 * 24 * 60 * 60 : apiUtil$1.isTestMode(req) ? 4 * 60 * 60 : appSetting.tokenExpireTime;
563
+ }
564
+ /**
565
+ * 获取用户令牌保存键
566
+ * @param token
567
+ * @returns {string}
568
+ */
569
+
570
+
571
+ static userTokenStoreKey(token) {
572
+ return "ut_" + token;
573
+ }
574
+ /**
575
+ * 获取机构令牌保存键
576
+ * @param token
577
+ * @returns {string}
578
+ */
579
+
580
+
581
+ static apiTokenStoreKey(token) {
582
+ return "api_" + token;
583
+ }
584
+ /**
585
+ * 判断是不是香港身份证
586
+ * @param idNum
587
+ * @returns {boolean}
588
+ */
589
+
590
+
591
+ static checkIsHKIC(idNum) {
592
+ return idNum.length === 8;
593
+ }
594
+ /**
595
+ * 将身份证号码暂存到用户信息中
596
+ * @param userInfo
597
+ * @param idNum
598
+ * @returns {*}
599
+ */
600
+
601
+
602
+ static setUserIdNo(userInfo, idNum) {
603
+ if (userInfo && idNum) {
604
+ userInfo._idNo = idNum;
605
+ userInfo.isHKIC = apiUtil$1.checkIsHKIC(idNum);
606
+ }
607
+
608
+ return userInfo;
609
+ }
610
+ /**
611
+ * 暂存令牌
612
+ * @param token
613
+ * @param tokenData
614
+ * @param dataId
615
+ * @param req
616
+ * @returns {Promise<void>}
617
+ */
618
+
619
+
620
+ static async storeToken(token, tokenData, dataId, req) {
621
+ // let timeout = tokenData.clientIp.substring(0, 8) == "192.168." ? 90 * 24 : 1;
622
+ let timeout = apiUtil$1.tokenExpireTime(req);
623
+
624
+ if (req.certPublicKey) {
625
+ tokenData.certPublicKey = req.certPublicKey;
626
+ }
627
+
628
+ kvStorage.storeObj(token, tokenData, timeout);
629
+
630
+ if (dataId) {
631
+ kvStorage.restoreValue("token_" + dataId).then(function (oldToken) {
632
+ if (oldToken !== token) {
633
+ kvStorage.unstoreValue(oldToken);
634
+ } else {
635
+ dataId = "";
636
+ }
637
+ }, function (e) {}).then(() => {
638
+ if (dataId !== "") kvStorage.storeValue("token_" + dataId, token, timeout);
639
+ });
640
+ }
641
+ }
642
+ /**
643
+ * 恢复令牌数据
644
+ * @param accessToken
645
+ * @param expireTime
646
+ * @returns {Promise<any>}
647
+ */
648
+
649
+
650
+ static async restoreTokenData(accessToken, expireTime) {
651
+ return await kvStorage.restoreObj(accessToken, expireTime);
652
+ }
653
+ /**
654
+ * 创建 API 调用记录
655
+ * @param tokenData
656
+ * @param req
657
+ * @returns {any}
658
+ */
659
+
660
+
661
+ static createApiCallRec(tokenData, req) {
662
+ if (!req.apiCallRec) {
663
+ if (req.apiCallRecId) {
664
+ return dbQueryOne(dbSql.loadApiUsage, {
665
+ replacements: {
666
+ id: req.apiCallRecId
667
+ }
668
+ }).then(rec => {
669
+ req.apiCallRec = rec;
670
+ return req.apiCallRec;
671
+ });
672
+ } else {
673
+ let params = extractParams(req); // let contentLength = parseInt(req.headers["content-length"]) || 0;
674
+
675
+ let rec = {
676
+ id: newGuid(),
677
+ companyId: tokenData.apiKey || '',
678
+ orderId: params.orderId || '',
679
+ signerId: params.signerId || '',
680
+ userId: params.userId || '',
681
+ contractName: params.contractName || '',
682
+ spOrderNum: params.spOrderNum || '',
683
+ notifyUri: params.notifyUri || '',
684
+ fileName: params.fileName || '',
685
+ fileHash: params.fileHash || '',
686
+ fileKeyHash: params.fileKeyHash || '',
687
+ fileSignedHash: params.fileSignedHash || '',
688
+ createTime: new Date(),
689
+ secret: tokenData.apiSecret || '',
690
+ fromIp: tokenData.clientIp || '',
691
+ method: req.method,
692
+ uri: req.route.path,
693
+ urlParams: req.url.split("?")[1] || "",
694
+ contentType: (req.headers["content-type"] || '').substring(0, 45),
695
+ // body: contentLength < 500 ? req.rawBody || '' : 'lob data, size:' + contentLength,
696
+ body: _getBodyLogStr(req),
697
+ resultCode: params.resultCode || '0',
698
+ resultInfo: params.resultInfo || '',
699
+ resultData: params.resultData || ''
700
+ };
701
+
702
+ if (rec.secret !== "") {
703
+ rec.secret = hb.getEncAse192(rec.secret);
704
+ }
705
+
706
+ req.apiCallRec = rec;
707
+ }
708
+ }
709
+
710
+ return req.apiCallRec;
711
+ }
712
+ /**
713
+ * 查询机构信息
714
+ * @param companyId
715
+ * @param nullable
716
+ * @returns {Promise<null|*>}
717
+ */
718
+
719
+
720
+ static async queryCompanyInfo(companyId, nullable) {
721
+ return await dbUtil.dbQueryOne(dbSql.queryCompanyInfo, {
722
+ companyId
723
+ }, nullable);
724
+ }
725
+ /**
726
+ * 获取企业有效证书
727
+ * @param companyId: 企业标识
728
+ */
729
+
730
+
731
+ static async getCompanyCertificate(companyId) {
732
+ let certInfo = {
733
+ // 正式启用的证书
734
+ certLiving: null,
735
+ certLivingId: '',
736
+ // 备用证书
737
+ certSpare: null,
738
+ certSpareId: ''
739
+ };
740
+ return await dbUtil.dbQueryOne(dbSql.queryCertDataByOwner, {
741
+ ownerId: companyId,
742
+ applyId: "company"
743
+ }, false).then(certRec => {
744
+ // console.log('当前证书:\n', certRec);
745
+ // checkCertStatus(certRec);
746
+ let certData = JSON.parse(certRec.certBody);
747
+ let pubKeyData = Buffer.from(certData.cert, "base64").toString(); // 公司正式证书
748
+
749
+ certInfo.certLiving = pubKeyData;
750
+ certInfo.certLivingId = certRec.id;
751
+ return dbUtil.dbQueryOne(dbSql.queryCertDataByOwner, {
752
+ ownerId: companyId,
753
+ applyId: "company_spare"
754
+ }, false).then(certRec1 => {
755
+ // console.log('备用证书:\n', certRec1);
756
+ // checkCertStatus(certRec1);
757
+ let certData1 = JSON.parse(certRec1.certBody);
758
+ let pubKeyData1 = Buffer.from(certData1.cert, "base64").toString(); // 公司备用证书
759
+
760
+ certInfo.certSpare = pubKeyData1;
761
+ certInfo.certSpareId = certRec1.id;
762
+ }).catch(e => {
763
+ // console.log('获取备用证书失败。', e);
764
+ certInfo.certSpare = null;
765
+ });
766
+ }).then(() => {
767
+ return certInfo;
768
+ }).catch(e => {
769
+ console.log('获取企业证书失败:\n', e);
770
+ throw [err.ACCESS_REFUSED, `获取企业证书失败:${err.ERROR(e).message}`];
771
+ });
772
+ }
773
+ /**
774
+ * 验证API调用签名
775
+ * @param tokenData
776
+ * @param req
777
+ * @returns {Promise<*|boolean>}
778
+ */
779
+
780
+
781
+ static async verifyApiSignature(tokenData, req) {
782
+ try {
783
+ if (!req.headers.timestamp) {
784
+ throw [err.ACCESS_REFUSED, `必须在请求头中设置时戳`];
785
+ }
786
+
787
+ let timestamp = parseInt(req.headers.timestamp);
788
+ let currentTime = new Date().valueOf();
789
+ let maxTimeDiff = apiUtil$1.isDebugMode(req) ? 7 * 24 * 3600 : apiUtil$1.isTestMode(req) ? 4 * 3600 : 100; // 100
790
+
791
+ if (timestamp.toString() == "NaN" || currentTime < timestamp - 5000 || currentTime - timestamp > maxTimeDiff * 1000) {
792
+ throw [err.ACCESS_REFUSED, `时戳(${timestamp})无效,当前时戳:${currentTime},时差 ${(currentTime - timestamp) / 1000}秒`];
793
+ }
794
+
795
+ let signature = req.headers.signature;
796
+
797
+ if (!signature) {
798
+ throw [err.ACCESS_REFUSED, `必须在请求头中提供签名`];
799
+ }
800
+
801
+ let signData = apiUtil$1.extractToken(req, null, true) || tokenData.apiKey;
802
+ signData += timestamp;
803
+
804
+ if (apiUtil$1.isDebugMode(req) || apiUtil$1.isTestMode(req)) {
805
+ let publicKey = req.headers.publickey || req.body.publicKey || req.query.publicKey;
806
+
807
+ if (publicKey) {
808
+ publicKey = decodeURIComponent(publicKey);
809
+ tokenData.certPublicKey = publicKey;
810
+ req.certPublicKey = publicKey;
811
+ }
812
+ }
813
+
814
+ if (tokenData.certPublicKey) {
815
+ let verifyResult = doVerify(signData, signature, tokenData.certPublicKey);
816
+ return await verifyResult;
817
+ }
818
+
819
+ return apiUtil$1.getCompanyCertificate(tokenData.apiKey).then(info => {
820
+ tokenData.certPublicKey = info.certLiving;
821
+ tokenData.certPublicKeySpare = info.certSpare;
822
+ tokenData.certLivingId = info.certLivingId;
823
+ tokenData.certSpareId = info.certSpareId;
824
+ req.certPublicKey = info.certLiving;
825
+ let token = apiUtil$1.extractToken(req, null, true);
826
+
827
+ if (token) {
828
+ apiUtil$1.storeToken(apiUtil$1.apiTokenStoreKey(token), tokenData, tokenData.apiKey, req);
829
+ }
830
+ }).then(() => {
831
+ return doVerify(signData, signature, tokenData.certPublicKey);
832
+ });
833
+ } catch (e) {
834
+ // return Promise.reject(e);
835
+ throw e;
836
+ }
837
+
838
+ function doVerify(signData, signature) {
839
+ let verify = crypto.createVerify('SHA256');
840
+ verify.write(signData);
841
+ verify.end();
842
+ let verifyOK = false;
843
+
844
+ try {
845
+ // 先用正式证书验证
846
+ verifyOK = verify.verify(tokenData.certPublicKey, signature, 'base64');
847
+ } catch (e) {
848
+ console.log("SPO服务签名验证异常(正式证书), ", e);
849
+ verifyOK = false;
850
+
851
+ if (!tokenData.certPublicKeySpare) {
852
+ throw {
853
+ eo: err.ACCESS_REFUSED,
854
+ msgArgv: "签名验证异常",
855
+ data: e
856
+ };
857
+ }
858
+ }
859
+
860
+ if (!verifyOK && tokenData.certPublicKeySpare) {
861
+ try {
862
+ // 再用备用证书验证
863
+ let verifySpare = crypto.createVerify('SHA256');
864
+ verifySpare.write(signData);
865
+ verifySpare.end();
866
+ verifyOK = verifySpare.verify(tokenData.certPublicKeySpare, signature, 'base64');
867
+
868
+ if (verifyOK) {
869
+ // 备用证书验证成功了,则将备用证书替换为正式证书
870
+ console.log(`公司(${tokenData.apiKey})备用证书验签成功,正式启用...`);
871
+ return dbUtil.dbTrans(trans => {
872
+ let p1 = dbUtil.dbExec(dbSql.deleteCertRecById, {
873
+ replacements: {
874
+ id: tokenData.certLivingId
875
+ },
876
+ transaction: trans
877
+ });
878
+ let p2 = dbUtil.dbExec(dbSql.spareCertToLiving, {
879
+ replacements: {
880
+ id: tokenData.certSpareId
881
+ },
882
+ transaction: trans
883
+ });
884
+ return Promise.all([p1, p2]);
885
+ }).then(() => {
886
+ tokenData.certPublicKey = tokenData.certPublicKeySpare;
887
+ delete tokenData.certLivingId;
888
+ delete tokenData.certSpareId;
889
+ delete tokenData.certPublicKeySpare;
890
+ let token = apiUtil$1.extractToken(req);
891
+
892
+ if (token) {
893
+ apiUtil$1.storeToken(apiTokenStoreKey(token), tokenData, tokenData.apiKey, req);
894
+ }
895
+
896
+ console.log(`公司(${tokenData.apiKey})备用证书成功转换为正式证书`);
897
+ });
898
+ }
899
+ } catch (e) {
900
+ console.log("SPO服务签名验证异常(备用证书), ", e);
901
+ throw {
902
+ eo: err.ACCESS_REFUSED,
903
+ msgArgv: "签名验证异常(spare)",
904
+ data: e
905
+ };
906
+ }
907
+ }
908
+
909
+ if (!verifyOK) {
910
+ console.log("SPO服务签名验证失败, tokenData: ", tokenData);
911
+ throw [err.ACCESS_REFUSED, "签名验证未通过"];
912
+ }
913
+
914
+ return verifyOK;
915
+ }
916
+ }
917
+ /**
918
+ * 检查API调用之合法性
919
+ * @param tokenData
920
+ * @param req
921
+ * @returns {Promise<any>}
922
+ */
923
+
924
+
925
+ static async checkApiCallValid(tokenData, req) {
926
+ if (!tokenData.companyInfo) {
927
+ tokenData.companyInfo = await apiUtil$1.queryCompanyInfo(tokenData.apiKey, true).catch(e => {
928
+ console.log("执行企业信息查询发生异常", e);
929
+ throw [err.API_KEY_INVALID, "执行企业信息查询发生异常:" + e.message || ""];
930
+ });
931
+ }
932
+
933
+ const companyInfo = tokenData.companyInfo;
934
+
935
+ if (companyInfo != null) {
936
+ let secret = apiUtil$1._getApiSecret(tokenData.apiKey);
937
+
938
+ if (secret !== tokenData.apiSecret) throw err.API_SCREPT_INVALID; // 不再检查 IP 白名单,改为验证证书签名
939
+ // console.log("fromIp:", tokenData.clientIp, "ipWhiteList:", companyInfo.ipWhiteList);
940
+ // let whiteList = companyInfo.ipWhiteList || "";
941
+ // // 没有设置ip白名单的就不检查了
942
+ // if (whiteList == "" || ipMatched(tokenData.clientIp, whiteList + ",127.0.0.1,1"))
943
+
944
+ if (apiUtil$1.signatureVerified()) return companyInfo;
945
+ return apiUtil$1.verifyApiSignature(tokenData, req).then(x => {
946
+ return companyInfo;
947
+ }, e => {
948
+ throw e;
949
+ });
950
+ }
951
+
952
+ throw [err.API_KEY_INVALID, tokenData.apiKey];
953
+ }
954
+ /**
955
+ * 检查令牌数据是否存在
956
+ * @param token
957
+ * @returns {*}
958
+ */
959
+
960
+
961
+ static tokenDataExist(token) {
962
+ return kvStorage.stored(token);
963
+ } //#endregion
964
+ //region ====中间件
965
+
966
+ /**
967
+ * 检查令牌,若存在则将其的用户信息置入req,否则返回错误信息
968
+ */
969
+
970
+
971
+ static async $checkToken(req, res, next) {
972
+ try {
973
+ await apiUtil$1.checkRequestToken(req);
974
+ return true;
975
+ } catch (e) {
976
+ res.send(err.ERROR(e));
977
+ return false;
978
+ }
979
+ }
980
+ /**
981
+ * 检查令牌,若存在则将其用户信息置入req
982
+ */
983
+
984
+
985
+ static async $getToken(req, res, next) {
986
+ function extractToken(req, res) {
987
+ if (!req.accessToken) {
988
+ //检查post的信息或者url查询参数或者头信息
989
+ let token = req.headers["access_token"] || req.headers['x-access-token']; //向后兼容
990
+
991
+ if (!token) {
992
+ let params = apiUtil$1.extractParams(req);
993
+ token = params["access_token"];
994
+
995
+ if (token) {
996
+ delete params["access_token"];
997
+ } else if (params.token) {
998
+ token = params.token; //向后兼容
999
+
1000
+ delete params.token; // } else if (res) {
1001
+ // // 如果没有token,则返回错误
1002
+ // console.log(err.TOKEN_NEEDED);
1003
+ // res.send(err.ERROR(err.TOKEN_NEEDED));
1004
+ }
1005
+ }
1006
+
1007
+ req.accessToken = token;
1008
+ }
1009
+
1010
+ return req.accessToken;
1011
+ }
1012
+
1013
+ try {
1014
+ if (extractToken(req, res)) {
1015
+ await apiUtil$1.restoreTokenData(apiUtil$1.userTokenStoreKey(req.accessToken), apiUtil$1.tokenExpireTime(req)).then(function (data) {
1016
+ req.userInfo = apiUtil$1.setUserIdNo(data, data._idNo);
1017
+ }, function (e) {//no token
1018
+ });
1019
+ }
1020
+
1021
+ return true;
1022
+ } catch (e) {
1023
+ res.send(err.ERROR(e));
1024
+ return false;
1025
+ }
1026
+ }
1027
+ /**
1028
+ * 标识此请求已经完成了签名验证或者无需进行签名验证
1029
+ */
1030
+
1031
+
1032
+ static $signatureVerified(req, res, next) {
1033
+ req.signatureVerified = true;
1034
+ return true;
1035
+ }
1036
+ /**
1037
+ * 标识此请求是从前端发过来的,比如移动端、PC浏览器等,区别于SPO一般的服务端后台请求。
1038
+ * 如果在请求参数中包含有签名参数,则将其移到请求头中
1039
+ */
1040
+
1041
+
1042
+ static $isMobile(req, res, next) {
1043
+ req.isMobile = true;
1044
+
1045
+ if (!req.signatureVerified) {
1046
+ let params = apiUtil$1.extractParams(req);
1047
+ moveProperty(params, req.headers, "access_token");
1048
+ moveProperty(params, req.headers, "timestamp");
1049
+
1050
+ if (moveProperty(params, req.headers, "signature")) {
1051
+ req.headers.signature = decodeURIComponent(req.headers.signature);
1052
+ }
1053
+ }
1054
+
1055
+ next();
1056
+ }
1057
+ /**
1058
+ * 检查企业 API 调用合法性 (apiKey, apiSecret)
1059
+ * @param req
1060
+ * @param res
1061
+ * @param next
1062
+ */
1063
+
1064
+
1065
+ static $checkApiKeyOld(req, res, next) {
1066
+ //检查post的信息或者url查询参数或者头信息
1067
+ let tokenData = apiUtil$1.extractTokenData(req);
1068
+ let params = apiUtil$1.extractParams(req);
1069
+ apiUtil$1.createApiCallRec(tokenData, req);
1070
+ let errResponse = null;
1071
+
1072
+ if (!tokenData.clientIp) {
1073
+ errResponse = apiUtil$1.spoApiFail(err.GET_CLIENTIP_FAIL, req);
1074
+ } else if (!tokenData.apiKey) {
1075
+ errResponse = apiUtil$1.spoApiFail([err.PARAMETER_NEEDED, "apiKey"], req);
1076
+ } else if (!tokenData.apiSecret) {
1077
+ errResponse = apiUtil$1.spoApiFail([err.PARAMETER_NEEDED, "apiSecret"], req);
1078
+ }
1079
+
1080
+ if (errResponse != null) {
1081
+ apiUtil$1._saveApiCallRec(req.apiCallRec, errResponse);
1082
+
1083
+ apiUtil$1.sendOrRedirect(req, res, errResponse);
1084
+ } else {
1085
+ apiUtil$1.checkApiCallValid(tokenData, req).then(companyInfo => {
1086
+ params.companyId = params.companyId || companyInfo.companyId;
1087
+ req.companyInfo = companyInfo;
1088
+ next();
1089
+ }, e => {
1090
+ console.log('apiCallInvalid:', e);
1091
+ let errResponse = spoApiFail(e, req);
1092
+
1093
+ apiUtil$1._saveApiCallRec(req.apiCallRec, errResponse);
1094
+
1095
+ apiUtil$1.sendOrRedirect(req, res, errResponse);
1096
+ });
1097
+ }
1098
+ }
1099
+ /**
1100
+ * 检查机构令牌
1101
+ */
1102
+
1103
+
1104
+ static $checkApiKey(req, res, next) {
1105
+ if (req.ignoreToken) {
1106
+ next();
1107
+ return;
1108
+ }
1109
+
1110
+ let accessToken = apiUtil$1.extractToken(req);
1111
+
1112
+ if (!accessToken) {
1113
+ res.send(apiUtil$1.spoApiFail(err.TOKEN_NEEDED, req)); // apiUtil.sendOrRedirect(req, res, spoApiFail(err.TOKEN_NEEDED, req));
1114
+
1115
+ return;
1116
+ }
1117
+
1118
+ apiUtil$1.restoreTokenData(apiUtil$1.apiTokenStoreKey(accessToken)).then(p => {
1119
+ // req.headers[hnApiKey] = p.apiKey || '';
1120
+ // req.headers[hnApiSecret] = p.apiSecret || '';
1121
+ if (req.isMobile) {
1122
+ // GET 请求的应该都是H5页面,由手机前端发起,需要把headers中的请求方ip换成服务端的
1123
+ // todo: 如何在API访问记录中记住请求者(手机端)的真实IP
1124
+ req.headers['x-phone-ip'] = hb.getClientIp(req);
1125
+ req.headers['x-real-ip'] = p.clientIp;
1126
+ } else {
1127
+ p.clientIp = hb.getClientIp(req);
1128
+ }
1129
+
1130
+ req.isApiCall = true;
1131
+ req.tokenData = p;
1132
+ apiUtil$1.$checkApiKeyOld(req, res, next);
1133
+ }).catch(e => {
1134
+ // res.send(hb.showError("授权令牌不存在或已过期"));
1135
+ // res.send(spoApiFail(err.TOKEN_INVALID, req));
1136
+ apiUtil$1.sendOrRedirect(req, res, apiUtil$1.spoApiFail(err.TOKEN_INVALID, req));
1137
+ });
1138
+ }
1139
+ /**
1140
+ * 检查请求令牌,允许个人用户令牌和机构令牌,若不存在或不合法,则返回错误信息
1141
+ * @param req
1142
+ * @param res
1143
+ * @param next
1144
+ * @returns {Promise<void|boolean|boolean|undefined>}
1145
+ */
1146
+
1147
+
1148
+ static async $checkTokenOrApiKey(req, res, next) {
1149
+ let accessToken = apiUtil$1.extractToken(req, res);
1150
+
1151
+ if (accessToken) {
1152
+ let tokenExist = await apiUtil$1.tokenDataExist(apiUtil$1.userTokenStoreKey(accessToken));
1153
+
1154
+ if (tokenExist) {
1155
+ return apiUtil$1.$checkToken(req, res, next);
1156
+ }
1157
+
1158
+ tokenExist = await apiUtil$1.tokenDataExist(apiUtil$1.apiTokenStoreKey(accessToken));
1159
+
1160
+ if (tokenExist) {
1161
+ return apiUtil$1.$checkApiKey(req, res, next);
1162
+ } // 如果给定的token不存在,看看是不是平台内部调用
1163
+
1164
+
1165
+ return await apiUtil$1.checkInternalToken(req).catch(e => {
1166
+ res.send(apiUtil$1.apiFail(e, req));
1167
+ return false;
1168
+ });
1169
+ }
1170
+ } //#endregion
1171
+
1172
+
1173
+ }
1174
+
1175
+ function configNeeded() {
1176
+ if (!conf || !err) {
1177
+ ppUtil$1.configNeeded();
1178
+ conf = ppUtil$1.appConfig;
1179
+ appSetting = conf.appSetting;
1180
+ err = ppUtil$1.appErrCfg;
1181
+ }
1182
+ }
1183
+
1184
+ var ppUtilApi = apiUtil$1;
1185
+
1186
+ const apiUtil = ppUtilApi;
1187
+ var ppUtil = {
1188
+ apiUtil
1189
+ };
1190
+
1191
+ export { ppUtil as default };