set-yoho-data.js
2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* 设置 YOHO 数据
* @author: 赵彪<bill.zhao@yoho.cn>
* @date: 2016/6/16
*/
'use strict';
const _ = require('lodash');
const net = require('net');
const _getClientIp = req => {
let remoteIp = req.get('X-Yoho-Real-IP') || req.get('X-Forwarded-For') || req.get('X-Real-IP') || req.ip;
if (remoteIp.indexOf(',') > 0) {
let arr = remoteIp.split(',');
remoteIp = _.trim(arr[0]);
}
if (_.startsWith(remoteIp, '10.66.')) {
remoteIp = req.get('X-Real-IP');
}
remoteIp = _.trim(remoteIp);
if (!net.isIPv4(remoteIp)) {
let ipv6String = remoteIp.split(':');
remoteIp = ipv6String[ipv6String.length - 1];
}
return remoteIp;
};
module.exports = (req, res, next) => {
req.user = {}; // 全局的用户数据
req.yoho = {}; // req和res绑定yoho对象,用于传递全局数据, 如req.yoho.channel等
// 判断请求是否来自app
let userAgent = req.get('User-Agent') || '';
// 判断请求是否来自app
req.yoho.isAliApp = /AliApp/i.test(userAgent);
req.yoho.isMiniApp = /miniProgram/i.test(userAgent) ||
req.query.client_type === 'miniapp';
req.yoho.isNowApp = /yohonow/i.test(userAgent);
req.yoho.isMarsApp = /yohomars/i.test(userAgent);
req.yoho.isYohoApp = /YohoBuy/i.test(userAgent);
req.yoho.isApp = req.yoho.isMiniApp ||
req.yoho.isNowApp ||
req.yoho.isMarsApp ||
req.yoho.isYohoApp;
req.yoho.isiOS = /(iPhone|iPad|iPod|iOS)/i.test(userAgent);
req.yoho.isAndroid = /Android/i.test(userAgent);
let clientType = '';
if (req.yoho.isAliApp) {
clientType = 'AliApp_';
} else if (req.yoho.isApp) {
clientType = 'YohoApp_';
} else {
clientType = 'Web_';
}
if (req.yoho.isiOS) {
clientType += 'iOS';
} else if (req.yoho.isAndroid) {
clientType += 'Android';
} else {
clientType += 'unknown';
}
req.yoho.clientType = clientType;
// client ip
req.yoho.clientIp = _getClientIp(req);
if (req.yoho.isApp) {
req.yoho.udid = _.get(req, 'query.udid', '');
}
if (!req.yoho.udid) {
req.yoho.udid = _.get(req, 'cookies.udid', '');
}
Object.assign(res.locals, req.yoho);
next();
};