@smart100/spu-web-plugin 1.0.0 → 1.0.3

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.
package/src/login.ts CHANGED
@@ -1,135 +1,128 @@
1
1
  import { cloneDeep } from 'lodash-es'
2
2
  import jwtDecode from 'jwt-decode'
3
- import { lsProxy, axios } from './index'
3
+ import { lsProxy } from './storageProxy'
4
+ import { axios } from './axios'
4
5
  import cloudServ from './cloudServ'
5
- // import { functionCheck } from './utils'
6
-
7
-
8
- // window.aPaaS = {
9
- // getWebInitParams (callback: any) {
10
- // callback && callback({
11
- // envname: 'xxx'
12
- // })
13
- // }
14
- // }
15
-
6
+ import core from './core'
7
+ import { urlquery } from './urlquery'
16
8
 
17
9
  type JwtResult = {
18
10
  LoginUser: IAny
19
11
  exp: number
20
12
  } | null
21
13
 
22
- class Login {
23
- private cache: IAny = {}
14
+ const cache: IAny = {}
24
15
 
25
- private getData (key: string) {
26
- if (this.cache[key]) {
27
- return this.cache[key]
28
- } else {
29
- const data = lsProxy.getItem(key)
30
- this.cache[key] = data
31
- return data
32
- }
16
+ function getData(key: string) {
17
+ if (cache[key]) {
18
+ return cache[key]
19
+ } else {
20
+ const data = lsProxy.getItem(key)
21
+ cache[key] = data
22
+ return data
33
23
  }
24
+ }
34
25
 
35
- private setData (key: string, value: any) {
36
- this.cache[key] = value
37
- lsProxy.setItem(key, value)
38
- }
26
+ function setData(key: string, value: any) {
27
+ cache[key] = value
28
+ lsProxy.setItem(key, value)
29
+ }
39
30
 
40
- private removeData (key: string) {
41
- delete this.cache[key]
42
- lsProxy.removeItem(key)
43
- }
31
+ function removeData(key: string) {
32
+ delete cache[key]
33
+ lsProxy.removeItem(key)
34
+ }
44
35
 
45
- async getEnvname (): Promise<string> {
46
- let envname = ''
47
-
48
- // web 查 context 的 envname
49
- let context: any = lsProxy.getItem('context')
50
- context && (context = JSON.parse(context))
51
- const contextEnvname = context?.envname || ''
52
-
53
- // 链接有些spu可能会传 envname
54
- const queryEnvname = this.getQueryEnvname()
55
-
56
- if (contextEnvname) {
57
- envname = contextEnvname
58
- } else if (queryEnvname) {
59
- envname = queryEnvname
60
- } else if (window?.aPaaS?.getWebInitParams && window?.Native?.setNavigationBarReturnButton) {
61
- // 手机端 查 envname
62
- // 只有手机端有 setNavigationBarReturnButton 方法
63
- envname = await new Promise((resolve, reject) => {
64
- window.aPaaS.getWebInitParams((params: any) => {
65
- resolve(params?.envname || '')
66
- })
36
+ async function getEnvname(): Promise<string> {
37
+ let envname = ''
38
+
39
+ // web 查 context 的 envname
40
+ let context: any = lsProxy.getItem('context')
41
+ context && (context = JSON.parse(context))
42
+ const contextEnvname = context?.envname || ''
43
+
44
+ // 链接有些spu可能会传 envname
45
+ const queryEnvname = getQueryEnvname()
46
+
47
+ if (contextEnvname) {
48
+ envname = contextEnvname
49
+ } else if (queryEnvname) {
50
+ envname = queryEnvname
51
+ } else if (window?.aPaaS?.getWebInitParams && window?.Native?.setNavigationBarReturnButton) {
52
+ // 手机端 查 envname
53
+ // 只有手机端有 setNavigationBarReturnButton 方法
54
+ envname = await new Promise((resolve, reject) => {
55
+ window.aPaaS.getWebInitParams((params: any) => {
56
+ resolve(params?.envname || '')
67
57
  })
68
- }
69
-
70
- return envname
58
+ })
71
59
  }
72
60
 
73
- setQueryEnvname (value: string) {
74
- this.setData('envname', value)
75
- }
61
+ return envname
62
+ }
76
63
 
77
- getQueryEnvname () {
78
- return this.getData('envname') || ''
79
- }
64
+ function setQueryEnvname(value: string) {
65
+ setData('envname', value)
66
+ }
80
67
 
81
- removeQueryEnvname () {
82
- this.removeData('envname')
83
- }
68
+ function getQueryEnvname() {
69
+ return getData('envname') || ''
70
+ }
84
71
 
85
- getToken () {
86
- return this.getData('token')
87
- // return lsProxy.getItem('token') as string
88
- }
72
+ function removeQueryEnvname() {
73
+ removeData('envname')
74
+ }
89
75
 
90
- setToken (value: string) {
91
- this.setData('token', value)
92
- }
76
+ function getToken() {
77
+ return getData('token')
78
+ // return lsProxy.getItem('token') as string
79
+ }
93
80
 
94
- removeToken () {
95
- this.removeData('token')
96
- }
81
+ function setToken(value: string) {
82
+ setData('token', value)
83
+ }
97
84
 
98
- getTokenExpires () {
99
- return this.getData('tokenexpires')
100
- }
85
+ function removeToken() {
86
+ removeData('token')
87
+ }
101
88
 
102
- setTokenExpires (value: string) {
103
- this.setData('tokenexpires', value)
104
- }
89
+ function getTokenExpires() {
90
+ return getData('tokenexpires')
91
+ // return lsProxy.getItem('tokenexpires') as string
92
+ }
105
93
 
106
- removeTokenExpires () {
107
- this.removeData('tokenexpires')
108
- }
94
+ function setTokenExpires(value: string) {
95
+ setData('tokenexpires', value)
96
+ }
109
97
 
110
- getRefreshToken () {
111
- return this.getData('refreshtoken')
112
- // return lsProxy.getItem('refreshtoken') as string
113
- }
98
+ function removeTokenExpires() {
99
+ removeData('tokenexpires')
100
+ }
114
101
 
115
- setRefreshToken (value: string) {
116
- this.setData('refreshtoken', value)
117
- }
102
+ function getRefreshToken() {
103
+ return getData('refreshtoken')
104
+ // return lsProxy.getItem('refreshtoken') as string
105
+ }
118
106
 
119
- removeRefreshToken () {
120
- this.removeData('refreshtoken')
121
- }
107
+ function setRefreshToken(value: string) {
108
+ setData('refreshtoken', value)
109
+ }
122
110
 
123
- updateToken () {
124
- // 如果是产品运营中心 则不走刷新token流程
125
- if (this.checkLogin() && this.getRole() === 'center') {
126
- console.warn('当前登录为产品运营中心用户,不支持自动刷新token。')
127
- return false
128
- }
129
- const token = this.getToken()
130
- const refreshtoken = this.getRefreshToken()
131
- const sendToken = this.checkLoginByToken(token) ? token : refreshtoken
132
- return axios.get('/api/auth/refreshtoken', {
111
+ function removeRefreshToken() {
112
+ removeData('refreshtoken')
113
+ }
114
+
115
+ function updateToken() {
116
+ // 如果是产品运营中心 则不走刷新token流程
117
+ if (checkLogin() && getRole() === 'center') {
118
+ console.warn('当前登录为产品运营中心用户,不支持自动刷新token。')
119
+ return false
120
+ }
121
+ const token = getToken()
122
+ const refreshtoken = getRefreshToken()
123
+ const sendToken = checkLoginByToken(token) ? token : refreshtoken
124
+ return axios
125
+ .get('/api/auth/refreshtoken', {
133
126
  params: {
134
127
  refreshtoken: sendToken
135
128
  },
@@ -139,404 +132,476 @@ class Login {
139
132
  headers: {
140
133
  token: sendToken
141
134
  }
142
- }).then((res: any) => {
135
+ })
136
+ .then((res: any) => {
143
137
  // console.log(res)
144
138
  const data = res?.data
145
139
  if (data) {
146
- this.setToken(data.token)
147
- this.setRefreshToken(data.refreshtoken)
148
- this.setTokenExpires(data.tokenexpires)
140
+ setToken(data.token)
141
+ setRefreshToken(data.refreshtoken)
142
+ setTokenExpires(data.tokenexpires)
149
143
  }
150
144
  })
151
- }
152
-
153
- private refreshtokenTimer: number | null = null
154
-
155
- startRefreshtoken () {
156
- // 如果是产品运营中心 则不走刷新token流程
157
- if (this.checkLogin() && this.getRole() === 'center') {
158
- console.warn('当前登录为产品运营中心用户,不支持自动刷新token。')
159
- return false
160
- }
145
+ }
161
146
 
162
- this.stopRefreshtoken()
163
-
164
- // 如果有登录 但 refreshtoken 不是完整 token 则10秒后【需要等单点登录走完后才刷新不然会被覆盖】刷新一次取到完整 token
165
- // 如果有登录 且 refreshtoken 是完整 token 如果剩余时间大于10分钟 则每隔10分钟刷一次 否则过期前15秒更新 token
166
- // 如果没登录 每隔1分钟走token更新逻辑(如果刚开始没登录 后面才登录【不需要再在登陆后写刷新token逻辑】)
167
- let time = 0
168
- if (this.checkLogin()) {
169
- const user = this.getUserByToken(this.getRefreshToken())
170
- if (user?.tokenId) {
171
- time = Number(this.getTokenExpires()) - Date.now() - 1000 * 15
172
- // 如果剩余时间大于10分钟 则每隔10分钟刷一次
173
- if (time > 600000) {
174
- time = 600000
175
- } else if (time < 0) {
176
- time = 0
177
- }
178
- } else {
179
- time = 10000
147
+ let refreshtokenTimer: number | null = null
148
+
149
+ function startRefreshtoken() {
150
+ // 如果是产品运营中心 则不走刷新token流程
151
+ if (checkLogin() && getRole() === 'center') {
152
+ console.warn('当前登录为产品运营中心用户,不支持自动刷新token。')
153
+ return false
154
+ }
155
+
156
+ stopRefreshtoken()
157
+
158
+ // 如果有登录 refreshtoken 不是完整 token 则10秒后【需要等单点登录走完后才刷新不然会被覆盖】刷新一次取到完整 token
159
+ // 如果有登录 且 refreshtoken 是完整 token 如果剩余时间大于10分钟 则每隔10分钟刷一次 否则过期前15秒更新 token
160
+ // 如果没登录 每隔1分钟走token更新逻辑(如果刚开始没登录 后面才登录【不需要再在登陆后写刷新token逻辑】)
161
+ let time = 0
162
+ if (checkLogin()) {
163
+ const user = getUserByToken(getRefreshToken())
164
+ if (user?.tokenId) {
165
+ time = Number(getTokenExpires()) - Date.now() - 1000 * 15
166
+ // 如果剩余时间大于10分钟 则每隔10分钟刷一次
167
+ if (time > 600000) {
168
+ time = 600000
169
+ } else if (time < 0) {
170
+ time = 0
180
171
  }
181
172
  } else {
182
- time = 60000
173
+ time = 10000
183
174
  }
184
- // time = 5000
185
- this.refreshtokenTimer = window.setTimeout(async () => {
186
- if (this.checkLogin()) {
187
- await this.updateToken()
188
- }
189
- this.startRefreshtoken()
190
- }, time)
175
+ } else {
176
+ time = 60000
191
177
  }
178
+ // time = 5000
179
+ refreshtokenTimer = window.setTimeout(async () => {
180
+ if (checkLogin()) {
181
+ await updateToken()
182
+ }
183
+ startRefreshtoken()
184
+ }, time)
185
+ }
192
186
 
193
- private stopRefreshtoken () {
194
- clearTimeout(this.refreshtokenTimer as number)
195
- this.refreshtokenTimer = null
187
+ function stopRefreshtoken() {
188
+ clearTimeout(refreshtokenTimer as number)
189
+ refreshtokenTimer = null
190
+ }
191
+
192
+ function getUser(key?: string): any {
193
+ const user = getData('user')
194
+ const userObj = user ? JSON.parse(user) : null
195
+ if (!key) {
196
+ return userObj
197
+ } else {
198
+ return userObj ? userObj[key] || '' : ''
196
199
  }
200
+ }
197
201
 
198
- getUser (key?: string): any {
199
- const user = this.getData('user')
200
- const userObj = user ? JSON.parse(user) : null
201
- if (!key) {
202
- return userObj
203
- } else {
204
- return userObj ? (userObj[key] || '') : ''
205
- }
202
+ function setUser(value: string | IAny) {
203
+ let res
204
+ if (typeof value === 'string') {
205
+ res = JSON.parse(value)
206
+ } else {
207
+ res = cloneDeep(value)
206
208
  }
207
209
 
208
- setUser (value: string | IAny) {
209
- let res
210
- if (typeof value === 'string') {
211
- res = JSON.parse(value)
212
- } else {
213
- res = cloneDeep(value)
214
- }
210
+ for (const x in res) {
211
+ res[x.toLowerCase()] = res[x]
212
+ }
215
213
 
216
- for (const x in res) {
217
- res[x.toLowerCase()] = res[x]
218
- }
214
+ setData('user', JSON.stringify(res))
215
+ }
219
216
 
220
- this.setData('user', JSON.stringify(res))
217
+ function setUserByToken(token: string) {
218
+ const user = getUserByToken(token)
219
+ if (user) {
220
+ setUser(user)
221
+ } else {
222
+ removeUser()
221
223
  }
224
+ }
222
225
 
223
- setUserByToken (token: string) {
224
- const user = this.getUserByToken(token)
225
- if (user) {
226
- this.setUser(user)
227
- } else {
228
- this.removeUser()
229
- }
226
+ function getUserByToken(token: string) {
227
+ const jwtInfo = parseToken(token)
228
+ if (jwtInfo && jwtInfo.LoginUser) {
229
+ return jwtInfo.LoginUser
230
+ } else {
231
+ return null
230
232
  }
233
+ }
231
234
 
232
- getUserByToken (token: string) {
233
- const jwtInfo = this.jwtDecode(token)
234
- if (jwtInfo && jwtInfo.LoginUser) {
235
- return jwtInfo.LoginUser
236
- } else {
237
- return null
238
- }
239
- }
235
+ function removeUser() {
236
+ removeData('user')
237
+ }
240
238
 
241
- removeUser () {
242
- this.removeData('user')
239
+ function parseToken(token?: string) {
240
+ if (!token) {
241
+ console.error('token为空 jwt解析token出错')
242
+ return null
243
243
  }
244
-
245
- private jwtDecode (token?: string) {
246
- if (!token) {
247
- console.error('token为空 jwt解析token出错')
248
- return null
249
- }
250
- try {
251
- return jwtDecode<JwtResult>(token)
252
- } catch (e) {
253
- console.error('jwt解析token出错', token, e)
254
- return null
255
- }
244
+ try {
245
+ return jwtDecode<JwtResult>(token)
246
+ } catch (e) {
247
+ console.error('jwt解析token出错', token, e)
248
+ return null
256
249
  }
250
+ }
257
251
 
258
- // // 产品运营中心token
259
- // {
260
- // "LoginUser": {
261
- // "appId": "100",
262
- // "tenantCode": "1656652",
263
- // "productCode": "100000000000000000",
264
- // "productVersionCode": null,
265
- // "clientTypeCode": null,
266
- // "userCode": "6",
267
- // "accountCode": "6",
268
- // "username": "庄焕滨",
269
- // "tokenId": "bd69b4a4-5376-47cd-91c3-f1e1576440e5",
270
- // "appCodes": null,
271
- // "appCode": null,
272
- // "platRoleCodes": ["1637696814759153664"],
273
- // "metamodeltype": 2,
274
- // "orgCode": "1751852081616130048",
275
- // "centerRole": true
276
- // },
277
- // "TwoFactorAuthCode": "6f56da978dffe31a3b03a56c446f9467",
278
- // "exp": 1751694745
279
- // }
280
-
281
- // // 租户token
282
- // {
283
- // "exp": 1720161305,
284
- // "LoginUser": {
285
- // "accountInfoCode": "1803686723986010112",
286
- // "accountCode": "1803686724107644928",
287
- // "tenantCode": "3000911",
288
- // "productCode": "100000000000000000",
289
- // "productVersionCode": "30000000000000911",
290
- // "clientTypeCode": 1,
291
- // "tokenId": "8614059e-69a5-4e1e-a948-f2ef680d0dd5",
292
- // "orgCode": "1803686397149065216",
293
- // "userInfoId": "1806591894588108800",
294
- // "userInfoName": "woOUQJEAAAn4r5-7jffaxad6yotbEZ5A",
295
- // "positionCode": "1803686397304254473",
296
- // "positionName": "系统管理员-勿删",
297
- // "memberCode": "1806591894659411968",
298
- // "refPositionCode": "1300728614534385664",
299
- // "categoryCode": "",
300
- // "orgStructTypeId": "1",
301
- // "userName": null,
302
- // "userName1": "woOUQJEAAAn4r5-7jffaxad6yotbEZ5A",
303
- // "userName2": null,
304
- // "userName3": null,
305
- // "tenantName": "智慧100-企微版-V9.1.1开发租户",
306
- // "appCode": "sales",
307
- // "appCodes": [
308
- // "promotion",
309
- // "distribution",
310
- // "sales"
311
- // ],
312
- // "subPdCodes": [
313
- // "sfa",
314
- // "dms",
315
- // "pmm",
316
- // "tpm",
317
- // "ai"
318
- // ],
319
- // "codepath": "1.1803686395634921472.1803686397149065216.",
320
- // "isleaforg": "true",
321
- // "metamodeltype": 1,
322
- // "isSmsLogin": false
323
- // }
324
- // }
325
- // 查询token所属登录角色
326
- // tenant: 普通租户登录 默认
327
- // center: 产品运营中心登录 单点登录时只带 token 没带 refreshtoken 和 tokenexpires
328
- getRoleByToken (token?: string) {
329
- let loginRole: 'center' | 'tenant' = 'tenant' // center | tenant
330
- if (token) {
331
- const jwtInfo = this.jwtDecode(token)
332
- if (jwtInfo?.LoginUser?.centerRole) {
333
- // 产品运营中心登录
334
- loginRole = 'center'
335
- }
252
+ // // 产品运营中心token
253
+ // {
254
+ // "LoginUser": {
255
+ // "appId": "100",
256
+ // "tenantCode": "1656652",
257
+ // "productCode": "100000000000000000",
258
+ // "productVersionCode": null,
259
+ // "clientTypeCode": null,
260
+ // "userCode": "6",
261
+ // "accountCode": "6",
262
+ // "username": "庄焕滨",
263
+ // "tokenId": "bd69b4a4-5376-47cd-91c3-f1e1576440e5",
264
+ // "appCodes": null,
265
+ // "appCode": null,
266
+ // "platRoleCodes": ["1637696814759153664"],
267
+ // "metamodeltype": 2,
268
+ // "orgCode": "1751852081616130048",
269
+ // "centerRole": true
270
+ // },
271
+ // "TwoFactorAuthCode": "6f56da978dffe31a3b03a56c446f9467",
272
+ // "exp": 1751694745
273
+ // }
274
+
275
+ // // 租户token
276
+ // {
277
+ // "exp": 1720161305,
278
+ // "LoginUser": {
279
+ // "accountInfoCode": "1803686723986010112",
280
+ // "accountCode": "1803686724107644928",
281
+ // "tenantCode": "3000911",
282
+ // "productCode": "100000000000000000",
283
+ // "productVersionCode": "30000000000000911",
284
+ // "clientTypeCode": 1,
285
+ // "tokenId": "8614059e-69a5-4e1e-a948-f2ef680d0dd5",
286
+ // "orgCode": "1803686397149065216",
287
+ // "userInfoId": "1806591894588108800",
288
+ // "userInfoName": "woOUQJEAAAn4r5-7jffaxad6yotbEZ5A",
289
+ // "positionCode": "1803686397304254473",
290
+ // "positionName": "系统管理员-勿删",
291
+ // "memberCode": "1806591894659411968",
292
+ // "refPositionCode": "1300728614534385664",
293
+ // "categoryCode": "",
294
+ // "orgStructTypeId": "1",
295
+ // "userName": null,
296
+ // "userName1": "woOUQJEAAAn4r5-7jffaxad6yotbEZ5A",
297
+ // "userName2": null,
298
+ // "userName3": null,
299
+ // "tenantName": "智慧100-企微版-V9.1.1开发租户",
300
+ // "appCode": "sales",
301
+ // "appCodes": [
302
+ // "promotion",
303
+ // "distribution",
304
+ // "sales"
305
+ // ],
306
+ // "subPdCodes": [
307
+ // "sfa",
308
+ // "dms",
309
+ // "pmm",
310
+ // "tpm",
311
+ // "ai"
312
+ // ],
313
+ // "codepath": "1.1803686395634921472.1803686397149065216.",
314
+ // "isleaforg": "true",
315
+ // "metamodeltype": 1,
316
+ // "isSmsLogin": false
317
+ // }
318
+ // }
319
+ // 查询token所属登录角色
320
+ // tenant: 普通租户登录 默认
321
+ // center: 产品运营中心登录 单点登录时只带 token 没带 refreshtoken 和 tokenexpires
322
+ function getRoleByToken(token?: string) {
323
+ let loginRole: 'center' | 'tenant' = 'tenant' // center | tenant
324
+ if (token) {
325
+ const jwtInfo = parseToken(token)
326
+ if (jwtInfo?.LoginUser?.centerRole) {
327
+ // 产品运营中心登录
328
+ loginRole = 'center'
336
329
  }
337
- return loginRole
338
330
  }
331
+ return loginRole
332
+ }
339
333
 
340
- getRole () {
341
- return this.getRoleByToken(this.getToken())
342
- }
334
+ function getRole() {
335
+ return getRoleByToken(getToken())
336
+ }
343
337
 
344
- // 检测当前用户是否登录状态
345
- checkLogin () {
346
- let haslogged = false
347
- const token = this.getToken()
348
- if (token) {
349
- if (this.getRole() === 'center') {
350
- haslogged = this.checkLoginByToken(token)
351
- } else {
352
- const refreshtoken = this.getRefreshToken()
353
- const tokenexpires = this.getTokenExpires()
354
- const now = Date.now()
355
- if (token && refreshtoken && tokenexpires && Number(tokenexpires) > now) {
356
- haslogged = this.checkLoginByToken(token)
357
- }
338
+ // 检测当前用户是否登录状态
339
+ function checkLogin() {
340
+ let haslogged = false
341
+ const token = getToken()
342
+ if (token) {
343
+ if (getRole() === 'center') {
344
+ haslogged = checkLoginByToken(token)
345
+ } else {
346
+ const refreshtoken = getRefreshToken()
347
+ const tokenexpires = getTokenExpires()
348
+ const now = Date.now()
349
+ if (token && refreshtoken && tokenexpires && Number(tokenexpires) > now) {
350
+ haslogged = checkLoginByToken(token)
358
351
  }
359
352
  }
360
- return haslogged
361
353
  }
354
+ return haslogged
355
+ }
362
356
 
363
- // 检测token是否过期
364
- checkLoginByToken (token?: string) {
365
- let haslogged = false
366
- if (token) {
367
- const now = Date.now()
368
- const jwtInfo = this.jwtDecode(token)
369
- if (jwtInfo?.exp) {
370
- haslogged = Number(jwtInfo.exp + '000') > now
371
- } else {
372
- haslogged = false
373
- }
357
+ // 检测token是否过期
358
+ function checkLoginByToken(token?: string) {
359
+ let haslogged = false
360
+ if (token) {
361
+ const now = Date.now()
362
+ const jwtInfo = parseToken(token)
363
+ if (jwtInfo?.exp) {
364
+ haslogged = Number(jwtInfo.exp + '000') > now
365
+ } else {
366
+ haslogged = false
374
367
  }
375
- return haslogged
376
368
  }
369
+ return haslogged
370
+ }
377
371
 
378
- // 接口请求回来的 userInfo 有 functioncodes 以便做权限校验
379
- // 有可能是中心角色请求失败 兼容不报错
380
- async getAndSetUserInfo () {
381
- try {
382
- const accountinfo = await axios.post('/api/teapi/rolepermission/account/getaccountinfo', {
383
- positionid: this.getUser('positioncode') || '',
372
+ // 接口请求回来的 userInfo 有 functioncodes 以便做权限校验
373
+ // 有可能是中心角色请求失败 兼容不报错
374
+ async function getAndSetUserInfo() {
375
+ try {
376
+ const accountinfo = await axios
377
+ .post('/api/teapi/rolepermission/account/getaccountinfo', {
378
+ positionid: getUser('positioncode') || '',
384
379
  deviceinfo: '',
385
380
  sysversion: '',
386
381
  clientversion: ''
387
- }).then((res: any) => {
382
+ })
383
+ .then((res: any) => {
388
384
  if (res.code === 200 && res.data) {
389
385
  return res.data
390
386
  } else {
391
387
  return null
392
388
  }
393
389
  })
394
- if (accountinfo) {
395
- this.setUser(accountinfo)
396
- }
397
- } catch (e) {
398
- console.error(e)
399
- console.warn('获取用户信息失败,当前您登录的帐号可能为非标准租户帐号。')
390
+ if (accountinfo) {
391
+ setUser(accountinfo)
400
392
  }
393
+ } catch (e) {
394
+ console.error(e)
395
+ console.warn('获取用户信息失败,当前您登录的帐号可能为非标准租户帐号。')
401
396
  }
397
+ }
402
398
 
403
- formatTenant (tenant: ITenantInfo) {
404
- if (!tenant) {
405
- return null
406
- }
407
- const cloundTagMap = ['storage', 'storage-1d', 'storage-1y', 'storage-3m']
408
- const result: NormalizedCloudServ = {}
409
- for (const keyItem of cloundTagMap) {
410
- const cloudServ = tenant.cloudserv[keyItem as StorageEnum]
411
- if (cloudServ) {
412
- result[keyItem as StorageEnum] = {
413
- cloudserv_storage_provider: cloudServ.provider,
414
- cloudserv_storage_storagebucket: cloudServ.storagebucket,
415
- cloudserv_storage_storageendpoint: cloudServ.storageendpoint,
416
- cloudserv_storage_storageurl: cloudServ.storageurl,
417
- cloudserv_storage_accesskeyid: cloudServ.accesskeyid,
418
- cloudserv_storage_region: cloudServ.region
419
- }
399
+ function formatTenant(tenant: ITenantInfo) {
400
+ if (!tenant) {
401
+ return null
402
+ }
403
+ const cloundTagMap = ['storage', 'storage-1d', 'storage-1y', 'storage-3m']
404
+ const result: NormalizedCloudServ = {}
405
+ for (const keyItem of cloundTagMap) {
406
+ const cloudServ = tenant.cloudserv[keyItem as StorageEnum]
407
+ if (cloudServ) {
408
+ result[keyItem as StorageEnum] = {
409
+ cloudserv_storage_provider: cloudServ.provider,
410
+ cloudserv_storage_storagebucket: cloudServ.storagebucket,
411
+ cloudserv_storage_storageendpoint: cloudServ.storageendpoint,
412
+ cloudserv_storage_storageurl: cloudServ.storageurl,
413
+ cloudserv_storage_accesskeyid: cloudServ.accesskeyid,
414
+ cloudserv_storage_region: cloudServ.region
420
415
  }
421
416
  }
422
- if (Object.keys(result).length === 0) {
423
- return null
424
- }
425
- return result
426
417
  }
418
+ if (Object.keys(result).length === 0) {
419
+ return null
420
+ }
421
+ return result
422
+ }
427
423
 
428
- async getAndSetTenant (tenantcode?: string) {
429
- try {
430
- const tenantsRes: null | ITenantInfo[] = await axios.get('/api/auth/tenantlist', {}).then((res: any) => {
431
- return res?.data?.tenants
432
- })
424
+ async function getAndSetTenant(tenantcode?: string) {
425
+ try {
426
+ const tenantsRes: null | ITenantInfo[] = await axios.get('/api/auth/tenantlist', {}).then((res: any) => {
427
+ return res?.data?.tenants
428
+ })
433
429
 
434
- let tenant: ITenantInfo | null = null
435
- if (tenantsRes?.length) {
436
- if (!tenantcode) {
437
- tenant = tenantsRes[0]
438
- } else {
439
- tenant = tenantsRes.find((item) => item.code === tenantcode) || null
440
- }
430
+ let tenant: ITenantInfo | null = null
431
+ if (tenantsRes?.length) {
432
+ if (!tenantcode) {
433
+ tenant = tenantsRes[0]
434
+ } else {
435
+ tenant = tenantsRes.find((item) => item.code === tenantcode) || null
441
436
  }
437
+ }
442
438
 
443
- if (!tenant) {
444
- lsProxy.removeItem('tenant')
445
- cloudServ.remove()
446
- } else {
447
- lsProxy.setItem('tenant', JSON.stringify(tenant))
448
- const normalizedTenant = this.formatTenant(tenant)
449
- if (normalizedTenant) {
450
- cloudServ.set(normalizedTenant)
451
- }
439
+ if (!tenant) {
440
+ lsProxy.removeItem('tenant')
441
+ cloudServ.remove()
442
+ } else {
443
+ lsProxy.setItem('tenant', JSON.stringify(tenant))
444
+ const normalizedTenant = formatTenant(tenant)
445
+ if (normalizedTenant) {
446
+ cloudServ.set(normalizedTenant)
452
447
  }
453
- } catch (e) {
454
- console.error(e)
455
- console.warn('获取租户信息失败,当前您登录的帐号可能为非标准租户帐号。')
456
448
  }
449
+ } catch (e) {
450
+ console.error(e)
451
+ console.warn('获取租户信息失败,当前您登录的帐号可能为非标准租户帐号。')
457
452
  }
453
+ }
458
454
 
459
- // 单点登录
460
- async singleLogin (query: IAny) {
461
- query = cloneDeep(query)
462
-
463
- let flag = false // 是否登录成功
464
- const token = query.token
465
- const refreshtoken = query.refreshtoken
466
- const tokenexpires = query.tokenexpires
467
- const envname = query.envname
468
- const context = query.context
469
-
470
- if (this.checkLoginByToken(token)) {
471
- let isneedlogin = true // 是否需要走单点登录流程
472
- const loginRole = this.getRoleByToken(token)
473
-
474
- if (loginRole === 'center') {
475
- // 如果本地已经登录 且 query 登录参数与本地一致 说明是刚登录没多久【token也没刷新过】 视为已经登录 不需再走单点登录流程
476
- // 之所以不强制校验 refreshtoken tokenexpires 是因为安装卸载配置页面有可能放在产品运营中心 没有这两字段
477
- if (this.checkLogin() && token === this.getToken()) {
478
- isneedlogin = false
479
- flag = true
480
- }
481
- } else {
482
- // 如果本地已经登录 且 query 登录参数与本地一致 说明是刚登录没多久【token也没刷新过】 视为已经登录 不需再走单点登录流程
483
- if (this.checkLogin() && token === this.getToken() && refreshtoken === this.getRefreshToken() && tokenexpires === this.getTokenExpires()) {
484
- isneedlogin = false
485
- flag = true
486
- }
455
+ // 单点登录
456
+ async function singleLogin(query: IAny) {
457
+ query = cloneDeep(query)
458
+
459
+ let flag = false // 是否登录成功
460
+ const token = query.token
461
+ const refreshtoken = query.refreshtoken
462
+ const tokenexpires = query.tokenexpires
463
+ const envname = query.envname
464
+ const context = query.context
465
+
466
+ if (checkLoginByToken(token)) {
467
+ let isneedlogin = true // 是否需要走单点登录流程
468
+ const loginRole = getRoleByToken(token)
469
+
470
+ if (loginRole === 'center') {
471
+ // 如果本地已经登录 且 query 登录参数与本地一致 说明是刚登录没多久【token也没刷新过】 视为已经登录 不需再走单点登录流程
472
+ // 之所以不强制校验 refreshtoken tokenexpires 是因为安装卸载配置页面有可能放在产品运营中心 没有这两字段
473
+ if (checkLogin() && token === getToken()) {
474
+ isneedlogin = false
475
+ flag = true
476
+ }
477
+ } else {
478
+ // 如果本地已经登录 且 query 登录参数与本地一致 说明是刚登录没多久【token也没刷新过】 视为已经登录 不需再走单点登录流程
479
+ if (
480
+ checkLogin() &&
481
+ token === getToken() &&
482
+ refreshtoken === getRefreshToken() &&
483
+ tokenexpires === getTokenExpires()
484
+ ) {
485
+ isneedlogin = false
486
+ flag = true
487
487
  }
488
+ }
489
+
490
+ if (isneedlogin) {
491
+ setToken(token)
492
+ setUserByToken(token) // 解析token为用户信息存入
493
+
494
+ refreshtoken ? setRefreshToken(refreshtoken) : removeRefreshToken()
495
+ tokenexpires ? setTokenExpires(tokenexpires) : removeTokenExpires()
496
+ envname ? setQueryEnvname(envname) : removeQueryEnvname()
497
+
498
+ // context 上下文字段 产品运营中心安装 卸载 配置 和 产品配置中心业务配置 页面需要用到
499
+ // web 端有传 app没传 需要做兼容
500
+ context && lsProxy.setItem('context', decodeURIComponent(context))
488
501
 
489
- if (isneedlogin) {
490
- this.setToken(token)
491
- this.setUserByToken(token) // 解析token为用户信息存入
492
-
493
- refreshtoken ? this.setRefreshToken(refreshtoken) : this.removeRefreshToken()
494
- tokenexpires ? this.setTokenExpires(tokenexpires) : this.removeTokenExpires()
495
- envname ? this.setQueryEnvname(envname) : this.removeQueryEnvname()
496
-
497
- // context 上下文字段 产品运营中心安装 卸载 配置 和 产品配置中心业务配置 页面需要用到
498
- // web 端有传 app没传 需要做兼容
499
- context && lsProxy.setItem('context', decodeURIComponent(context))
500
-
501
- // 单点登录写入 token 之后 换取完整的 refreshtoken
502
- try {
503
- if (this.checkLogin()) {
504
- const user = this.getUserByToken(this.getRefreshToken())
505
- if (!user?.tokenId) {
506
- this.updateToken()
507
- }
502
+ // 单点登录写入 token 之后 换取完整的 refreshtoken
503
+ try {
504
+ if (checkLogin()) {
505
+ const user = getUserByToken(getRefreshToken())
506
+ if (!user?.tokenId) {
507
+ updateToken()
508
508
  }
509
- } catch (err) {
510
- console.error(err)
511
509
  }
510
+ } catch (err) {
511
+ console.error(err)
512
+ }
512
513
 
513
- // 这里兼容报错
514
- await this.getAndSetTenant()
515
- await this.getAndSetUserInfo()
514
+ // 这里兼容报错
515
+ await getAndSetTenant()
516
+ await getAndSetUserInfo()
516
517
 
517
- flag = true
518
- }
519
- } else {
520
- flag = false
521
- console.error('没传 token 或所传 token 已过期,无法单点登录。')
518
+ // 单点登录后 获取 web 开发者模式 如果是则设置 isdebugger
519
+ urlquery.dealWebDebugger()
520
+
521
+ flag = true
522
522
  }
523
+ } else {
524
+ flag = false
525
+ console.error('没传 token 或所传 token 已过期,无法单点登录。')
526
+ }
523
527
 
524
- // 单点登录后 无论是否成功 都需要删除 query 中相关参数
525
- token && delete query.token
526
- refreshtoken && delete query.refreshtoken
527
- tokenexpires && delete query.tokenexpires
528
- envname && delete query.envname
529
- context && delete query.context
528
+ // 单点登录后 无论是否成功 都需要删除 query 中相关参数
529
+ token && delete query.token
530
+ refreshtoken && delete query.refreshtoken
531
+ tokenexpires && delete query.tokenexpires
532
+ envname && delete query.envname
533
+ context && delete query.context
530
534
 
531
- // debugger
535
+ // debugger
532
536
 
533
- return {
534
- flag,
535
- query
536
- }
537
+ return {
538
+ flag,
539
+ query
537
540
  }
538
541
  }
539
542
 
540
- const login = new Login()
543
+ function installAuth(options: any) {
544
+ startRefreshtoken()
545
+ if (options.router) {
546
+ options.router.beforeEach(async (to: any, from: any, next: any) => {
547
+ // console.log(from)
548
+ // console.log(to)
549
+ // const isInitVisit = from.path === '/' && from.name === undefined // 路由初始化访问
550
+ // console.log('isInitVisit', isInitVisit)
551
+
552
+ // 自动登录
553
+ if (to.query.token) {
554
+ const singleLoginRes = await singleLogin(to.query)
555
+ if (singleLoginRes.flag) {
556
+ // debugger
557
+ // next()
558
+ await core.initGetData()
559
+ next({
560
+ path: to.path,
561
+ params: to.params,
562
+ query: singleLoginRes.query
563
+ })
564
+ } else {
565
+ console.error('单点登录失败,请检查链接所传 token 是否非法或过期。')
566
+ next()
567
+ }
568
+ } else {
569
+ next()
570
+ }
571
+ })
572
+ } else {
573
+ console.warn(
574
+ '@smart100/spu-web-plugin 需要传入一个 vue-router 实例以便执行单点登录逻辑,如果您没传 vue-router 实例则需要自行在合适的位置执行单点登录代码。'
575
+ )
576
+ }
541
577
 
542
- export default login
578
+ if (checkLogin()) {
579
+ core.initGetData()
580
+ }
581
+ }
582
+
583
+ export {
584
+ installAuth,
585
+ getEnvname,
586
+ getToken,
587
+ // setToken,
588
+ // removeToken,
589
+ getTokenExpires,
590
+ // setTokenExpires,
591
+ // removeTokenExpires,
592
+ getRefreshToken,
593
+ // setRefreshToken,
594
+ // removeRefreshToken,
595
+ updateToken,
596
+ // startRefreshtoken,
597
+ // stopRefreshtoken,
598
+ getUser,
599
+ // setUser,
600
+ getRole,
601
+ // removeUser,
602
+ // getUserByToken,
603
+ // setUserByToken,
604
+ checkLogin,
605
+ // checkLoginByToken,
606
+ singleLogin
607
+ }