ssoInit.js
20.4 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
window.onerror = function (msg, url, line, col, error) {
window.localStorage['emDebug'] == '1' && alert(JSON.stringify(arguments))
};
(function () {
var getJSONObj = function (key) {
if (!window.localStorage[key]) {
return null;
}
try {
return JSON.parse(window.localStorage[key]);
}
catch (e) {
return {};
}
};
var getFd = function (values) {
var fd = '';
for (var p in values) {
if (values.hasOwnProperty(p)) {
var target = values[p];
target = target === void 0 ? '' : target;
var item = encodeURIComponent(target);
fd += p + '=' + item + '&';
}
}
return fd;
}.bind(this);
var checkReject = function (obj) {
var isFalse = false;
if (obj.errorCode && obj.errorCode === '001') { // session异常
console && console.log('session过期');
isFalse = true;
}
else if (obj.errorCode && obj.errorCode === '002') { // session异常
console && console.log('登陆超时');
isFalse = true;
}
else if (typeof obj.status !== 'undefined' && (!obj.status || obj.status === 'false')) {
console && console.log(JSON.stringify(obj));
isFalse = true;
}
return isFalse;
};
var callApi = function (options) {
var url = options.url || '';
var method = options.method || 'GET';
var params = options.params || {};
var type = options.type || 'json';
var includeCredentials = options.includeCredentials !== false ? true : false;
var useJson = options.useJson || false;
var _url = url;
var server = window.server || '';
var ua = window.navigator.userAgent;
var inMobile = (/.*E-Mobile7.*/.test(ua)
|| /.*E-Mobile\/7.*/.test(ua)
|| /.*MicroMessenger.*/.test(ua)
|| /.*DingTalk.*/.test(ua)
|| /Qing\/.*;(iOS|iPhone|Android).*/.test(ua)
|| /.*e-mobile-xp.*/.test(ua)
|| /.*HuaWei-AnyOffice.*/.test(ua)
)
if(inMobile) {
params._ec_ismobile = true;
params._ec_browser = ua.browser;
params._ec_browserVersion = ua.version;
params._ec_os = ua.os;
params._ec_osVersion = ua.osVersion;
params.ismobile = 1;
}
if (/\?/.test(_url)) {
var urlParams = getFrameParams(_url);
_url = _url.slice(0, url.indexOf('?'))
// params = Object.assign({}, params, urlParams);
for (var key in urlParams) {
if (urlParams.hasOwnProperty(key)) {
var element = urlParams[key];
params[key] = element;
}
}
}
if (getJSONObj('customSessionKey')) {
var customSessionKey = getJSONObj('customSessionKey');
params[customSessionKey.keyName] = customSessionKey.keyValue;
}
if (window.wm_test_accesskey) {
params['wm_test_accesskey'] = window.wm_test_accesskey;
}
_url = server + _url;
if (method.toUpperCase() === 'GET' && Object.keys(params).length > 0) {
var c = '?';
if (/\?/.test(_url)) {
c = '&';
}
_url = _url + c + getFd(params);
}
if (method.toUpperCase() === 'GET' && !/__random__/.test(_url)) {
var c = '?';
if (/\?/.test(_url)) {
c = '&';
}
_url += c + '__random__=' + new Date().getTime();
}
function evil(fn) {
var Fn = Function; // 一个变量指向Function,防止有些前端编译工具报错
return new Fn('return ' + fn)();
}
if (window.e9ssoMobileConfig && window.e9ssoMobileConfig.inUse && window.e9ssoMobileConfig.callapi_params_handler) {
var res = window.e9ssoMobileConfig.callapi_params_handler(_url, method, params, includeCredentials, useJson);
_url = res.url;
method = res.method;
params = res.params;
includeCredentials = res.includeCredentials;
useJson = res.useJson;
}
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method.toUpperCase(), _url, true);
if (useJson === false) {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
} else {
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
}
if (window.localStorage.emToken) {
// xhr.setRequestHeader("ecemtoken", window.localStorage.emToken);
window.localStorage.removeItem('ecemtoken')
}
xhr.withCredentials = includeCredentials;
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = xhr.responseText;
if (window.e9ssoMobileConfig && window.e9ssoMobileConfig.inUse && window.e9ssoMobileConfig.callapi_response_handler) {
data = window.e9ssoMobileConfig.callapi_response_handler(data, reject, xhr.response);
}
if (type === 'json' && typeof (data) === 'string') {
try {
data = JSON.parse(data);
} catch (error) {
data = data || '{}';
data = evil('(' + data + ')'); // JSON.parse 解析反斜杠报错处理
alert('fetch 数据处理异常: ' + error);
}
}
if (data.em_url_open) {
window.em_url_open = data.em_url_open;
}
if (data.emobile_ec_id) {
window.localStorage.emobile_ec_id = data.emobile_ec_id
}
// // 单点登录接口返回 code无效单独处理
// if (
// (data.status === "false" || !data.status) &&
// data.msg &&
// /\"errcode\"\:91011/.test(data.msg)
// ) {
// // alert("登陆超时,请关闭页面重新打开");
// // reject(url + 'fetch 请求异常: ' + (data.errorCode || JSON.stringify(data)));
// reject("登陆超时,请关闭页面重新打开");
// }
if (type === 'json' && data && data.status === 'false') {
resolve(data);
console && console.log('数据异常:' + JSON.stringify(data));
}
else if (!data.status && (data.showMsg || data.showType === 'msg')) {
resolve(data);
alert('数据异常:' + JSON.stringify(data));
}
else if (!data.status && (data.showModal || data.showType === 'modal')) {
resolve(data);
alert('数据异常:' + JSON.stringify(data));
}
else if (type === 'json' && checkReject(data)) {
console && console.log('数据异常:' + JSON.stringify(data));
if (/.*MicroMessenger.*/.test(ua) && window.em_url_open) {
window.location.href = window.em_url_open + '/wxapi/wxclienturl/redirect?em_sys_id=' + window.localStorage.emobile_ec_id + '&redirect_url=' + encodeURIComponent(location.href)
}
reject(url + 'fetch 请求异常: ' + (data.errorCode || JSON.stringify(data)));
}
else {
resolve(data);
}
}
}
xhr.send(getFd(params));
}.bind(this));
};
var loadEmFile = function(res, rs, rj, emUrl) {
loadjs.isDefined('em')
? loadjs.ready('em', function () {initEM(res, rs, rj, false, emUrl); }.bind(this))
: loadjs(emUrl, 'em', {
success: function () { window.wm_test_sso_em_loaded_end = new Date().getTime(); initEM(res, rs, rj, false, emUrl); }.bind(this),
error: function (res) {
if (/^https/.test(location.href) !== /^https/.test(emUrl)) {
rj({ msg: 'jem.js 加载失败:em与ec协议不一致'});
} else {
rj({ msg: 'jem.js 加载失败:' + emUrl });
}
}.bind(this),
numRetries: 2
});
}
var ssoInit = function (emCode) {
if (emCode === undefined) {
emCode = '';
}
return new Promise(function (rs, rj) {
var params = getFrameParams();
var ua = window.navigator.userAgent;
var loadJem = (/.*E-Mobile7.*/.test(ua)
|| /.*E-Mobile\/7.*/.test(ua)
|| /.*MicroMessenger.*/.test(ua)
|| /.*DingTalk.*/.test(ua)
|| /Qing\/.*;(iOS|iPhone|Android).*/.test(ua)
|| /.*e-mobile-xp.*/.test(ua)
|| /.*HuaWei-AnyOffice.*/.test(ua)
)
if ((params.em_auth_code && params.em_auth_code != 'undefined') || loadJem) {
if (parseInt(window.localStorage['em_retry_time']) >= 3) {
window.localStorage['em_retry_time'] = 0;
rj();
} else {
if (window.localStorage['em_retry_time']) {
window.localStorage['em_retry_time'] = parseInt(window.localStorage['em_retry_time'] + 1);
} else {
window.localStorage['em_retry_time'] = 0;
}
}
try {
var tempParams = params;
var code = emCode || params.em_auth_code
// tempParams = Object.assign(tempParams, { em_auth_code: code });
tempParams.em_auth_code = code
var codeList = window.emCodeList || [];
if (codeList.some(function (codeUsed) { code == codeUsed })) {
tempParams = {};
}
tempParams.em_auth_userid = params.em_auth_userid
tempParams.timeZoneOffset = new Date().getTimezoneOffset();
codeList.push(code);
window.emCodeList = codeList;
callApi({
url: '/api/ec/dev/app/test',
method: 'GET',
params: tempParams,
type: 'json',
}).then(function (res) {
window.wm_test_sso_api_end = new Date().getTime();
window.localStorage['em_retry_time'] = 0;
window.em_url_open = res.em_url_open;
if (res.status === true || res.status === '1') {
if (!res.em_url_open) {
rs();
return;
}
var emUrl = res.em_url_open + '/open/js/jem.js?v=' + new Date().getTime();
// if (res.jemUrl) {
// emUrl = res.jemUrl
// }
try {
loadEmFile(res, rs, rj, emUrl);
} catch (error) {
rj({ msg: 'js 加载异常:' + res.em_url_open })
}
} else {
rj({ msg: '认证失败,em地址:' + res.em_url, res: res });
}
}.bind(this)).catch(function (error) {
if (/.*MicroMessenger.*/.test(ua) && window.em_url_open) {
window.location.href = window.em_url_open + '/wxapi/wxclienturl/redirect?em_sys_id=' + window.localStorage.emobile_ec_id + '&redirect_url=' + encodeURIComponent(location.href)
}
if (window.em && window.em.checkJsApi("getEmAuthCode")) {
window.em.getEmAuthCode({
sysId: window.localStorage.emobile_ec_id, // 集成系统ID
success: function (emres) {
// 如:{"em_auth_code":"abc123","errMsg":"getEmAuthCode:ok"}
if (emres.em_auth_code) {
ssoInit(emres.em_auth_code)
} else {
alert('重新获取em_auth_code失败');
}
},
error: function (error) {
alert('重新获取em_auth_code失败: ' + JSON.stringify(error));
}
});
} else {
reinitEm()
rj();
}
}.bind(this));
} catch (error) {
window.localStorage['emDebug'] == '1' && alert(error);
}
}
else {
try {
checkCustomSSO(rs, rj)
} catch (error) {
rj({ msg: '自定义配置 加载异常' + error })
}
}
}.bind(this));
}.bind(this);
var checkCustomSSO = function (rs, rj) {
// 移动端单点登录自定义配置
if (window.e9ssoMobileConfig && window.e9ssoMobileConfig.inUse) {
// 移动端单点登录自定义初始化方法
window.e9ssoMobileConfig.customInit().then(function () {
if (!window.ssoCustomChecked && !window.localStorage.ssoCustomChecked) {
window.ssoCustomChecked = true;
if (window.customSsoConfig) {
// 移动端自定义单点登录接口
if (window.customSsoConfig.inUseMobile) {
var params = getFrameParams();
var checkSessionParams = [];
if (window.customSsoConfig.sessionCheckApiParamsMobile) {
var sessionParams = window.customSsoConfig.sessionCheckApiParamsMobile.split(',');
sessionParams.forEach(function (element) {
checkSessionParams[element] = params[element];
}.bind(this));
}
callApi({
url: window.customSsoConfig.sessionCheckApiMobile,
method: window.customSsoConfig.sessionCheckApiMobileType,
params: checkSessionParams,
type: 'json',
}).then(function (res) {
if ((res.status === '1' || res.status === true) && !res.hasSession) {
var service = escape(window.location.href);
var paramsMark = '?';
if (window.customSsoConfig.serverLoginUrlMobile.indexOf('?') !== -1) {
paramsMark = '&';
}
window.location.href = window.customSsoConfig.serverLoginUrlMobile + paramsMark + 'service=' + service;
rs();
}
else {
rj('sessionCheckApiMobile');
}
}.bind(this));
}
else {
rs();
}
}
else {
rs();
}
}
else {
if (window.localStorage.ssoCustomChecked) {
window.localStorage.ssoCustomChecked = false;
}
rs();
}
}.bind(this)).catch(function (res) { rj('customInit' + JSON.stringify(res)); }.bind(this));
}
else {
if (!window.ssoCustomChecked && !window.localStorage.ssoCustomChecked) {
window.ssoCustomChecked = true;
if (window.customSsoConfig) {
// 移动端自定义单点登录接口
if (window.customSsoConfig.inUseMobile) {
var params = getFrameParams();
var checkSessionParams = [];
if (window.customSsoConfig.sessionCheckApiParamsMobile) {
var sessionParams = window.customSsoConfig.sessionCheckApiParamsMobile.split(',');
sessionParams.forEach(function (element) {
checkSessionParams[element] = params[element];
}.bind(this));
}
callApi({
url: window.customSsoConfig.sessionCheckApiMobile,
method: window.customSsoConfig.sessionCheckApiMobileType,
params: checkSessionParams,
type: 'json',
}).then(function (res) {
if ((res.status === '1' || res.status === true) && !res.hasSession) {
var service = escape(window.location.href);
var paramsMark = '?';
if (window.customSsoConfig.serverLoginUrlMobile.indexOf('?') !== -1) {
paramsMark = '&';
}
window.location.href = window.customSsoConfig.serverLoginUrlMobile + paramsMark + 'service=' + service;
rs();
}
else {
rj('sessionCheckApiMobile');
}
}.bind(this));
}
else {
rs();
}
}
else {
rs();
}
}
else {
if (window.localStorage.ssoCustomChecked) {
window.localStorage.ssoCustomChecked = false;
}
rs();
}
}
}.bind(this);
var getFrameParams = function (urlStr) {
var url = urlStr || window.location.href;
var params = {};
var urlParams = [];
if (url.indexOf('#') !== -1) {
var paramsArr = url.split('#');
paramsArr.forEach(function(item) {
if (item.indexOf('?') !== -1) {
var urlItem = item.slice(item.indexOf('?') + 1).split('&');
urlItem.forEach(function (element) {
var datas = element.split('=');
params[datas[0]] = datas[1];
}.bind(this));
}
}.bind(this))
} else {
urlParams = url.slice(url.indexOf('?') + 1).split('&');
urlParams.forEach(function (element) {
var datas = element.split('=');
params[datas[0]] = datas[1];
}.bind(this));
}
return params;
}.bind(this);
var initEM = function (res, rs, rj, isReload, emUrl) {
try {
var loadEm = function (retryTimes) {
var retryDelay = 100;
if (retryTimes === 0) {
retryDelay = 0;
}
setTimeout(function () {
// init emobile config
if (window.em) {
window.em.config({
corpId: res.em_corpid,
appId: '',
});
window.localStorage.emobile_ec_id = res.ec_id;
rs(res);
}
else {
if (retryTimes < 2) {
loadEm(retryTimes + 1);
}
else {
if (isReload) {
// loadEm(0);
rj({ msg: 'em对象不存在,重新加载无效' });
} else {
reloadEm(res, rs, rj, emUrl);
}
}
}
}.bind(this), retryDelay);
}.bind(this);
loadEm(0);
} catch (error) {
window.localStorage['emDebug'] == '1' && alert(error);
}
}.bind(this);
var reinitEm = function() {
callApi({
url: '/api/ec/dev/app/test',
method: 'GET',
params: {},
type: 'json',
}).then(function (res) {
if (res.status === true || res.status === '1') {
if (!res.em_url_open) {
return;
}
var emUrl = res.em_url_open + '/open/js/jem.js?v=' + new Date().getTime();
var rj = function(params) {
alert(JSON.stringify(params))
}.bind(this)
var rs = function() {
window.em.getEmAuthCode({
sysId: window.localStorage.emobile_ec_id, // 集成系统ID
success: function (emres) {
// 如:{"em_auth_code":"abc123","errMsg":"getEmAuthCode:ok"}
if (emres.em_auth_code) {
ssoInit(emres.em_auth_code).then(function() {
window.location.reload();
})
} else {
alert('重新获取em_auth_code失败');
}
},
error: function (error) {
alert('重新获取em_auth_code失败: ' + JSON.stringify(error));
}
});
}
try {
loadEmFile(res, rs, rj, emUrl);
} catch (error) {
rj({ msg: 'js 加载异常' + error })
}
}
else {
// alert({ msg: '重认证失败,' + res.errmsg, res: res });
alert('重认证失败:' + res.em_url)
}
}.bind(this));
}.bind(this)
var reloadEm = function (res, rs, rj, emUrl) {
loadjs((emUrl + 'reload'), 'em', {
success: function () { window.wm_test_sso_em_loaded_end = new Date().getTime(); initEM(res, rs, rj, true, emUrl); }.bind(this),
error: function (res) {
rj({ msg: (('jem.js 重载失败:' + res.em_url_open) || 'jem.js 重载失败,emUrl:' + emUrl)});
}.bind(this)
})
}
window.em_ssoInit = ssoInit;
window.sso_callApi = callApi;
window.sso_getJSONObj = getJSONObj;
try {
var loadDevFile = function () {
var defaultDevFiles = [
"/cloudstore/config/devStatic/devModuleCustomMobile.js?v=" + new Date().getTime(),
"css!/cloudstore/config/devStatic/devModuleStyleMobile.css?v=" + new Date().getTime()
];
if (window.ecDevFileConfig && window.ecDevFileConfig.mobile) {
if (window.ecDevFileConfig.mobile.global) {
defaultDevFiles = window.ecDevFileConfig.mobile.global;
}
if (window.ecDevFileConfig.mobile.moduleConfig && window.ecDevFileConfig.mobile.moduleConfig.length) {
var moduleConfigList = window.ecDevFileConfig.mobile.moduleConfig
for (var index = 0; index < moduleConfigList.length; index++) {
var element = moduleConfigList[index];
if (window.location.href.search(element.hrefRegex) > 0) {
defaultDevFiles = defaultDevFiles.concat(element.files);
}
}
}
}
loadjs.isDefined('customDevFiles') ? '' : loadjs(defaultDevFiles, 'customDevFiles');
}
loadDevFile();
} catch (error) {
window.localStorage['emDebug'] == '1' && alert('customDevFiles error')
console && console.log(error)
}
})()