universal-auth-manager.js
14.6 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
/*
* @Description: 通用静默授权管理器 - 解耦版本
* @Author: 基于老来赛项目的静默授权功能重构
* @Date: 2025-01-25
*/
/**
* 通用授权管理器类
* 通过配置参数适配不同项目的需求
*/
export class UniversalAuthManager {
constructor(config = {}) {
// 默认配置
this.config = {
// 授权接口配置
authUrl: '/srv/?a=openid',
// 页面路径配置
authPage: '/pages/auth/index',
defaultPage: '/pages/index/index',
// 存储配置
sessionKey: 'sessionid',
routeKey: 'saved_route',
// 测试环境配置
testOpenIds: [],
// 请求超时配置
timeout: 5000,
// 加载提示配置
loadingText: '加载中...',
// 自定义钩子函数
onAuthSuccess: null,
onAuthError: null,
checkUserStatus: null, // 用户状态检查函数
getRedirectPath: null, // 获取重定向路径函数
// 适配器接口
storageAdapter: null,
httpAdapter: null,
navigatorAdapter: null,
platformAdapter: null,
// 合并用户配置
...config
}
// 验证必需的适配器
this._validateAdapters()
}
/**
* 验证必需的适配器是否已提供
* @private
*/
_validateAdapters() {
const requiredAdapters = ['storageAdapter', 'httpAdapter', 'navigatorAdapter', 'platformAdapter']
for (const adapter of requiredAdapters) {
if (!this.config[adapter]) {
throw new Error(`缺少必需的适配器: ${adapter}`)
}
}
}
/**
* 检查是否需要授权
* @returns {boolean} 是否需要授权
*/
needAuth() {
try {
const sessionid = this.config.storageAdapter.get(this.config.sessionKey)
return !sessionid || sessionid === ''
} catch (error) {
console.error('检查授权状态失败:', error)
return true
}
}
/**
* 静默授权
* @param {Function} onSuccess - 成功回调
* @param {Function} onError - 失败回调
* @returns {Promise} 授权结果
*/
async silentAuth(onSuccess, onError) {
return new Promise((resolve, reject) => {
// 检查是否已经授权
if (!this.needAuth()) {
const result = { code: 1, msg: '已授权' }
if (onSuccess) onSuccess(result)
resolve(result)
return
}
// 显示loading提示
this.config.platformAdapter.showLoading({
title: this.config.loadingText,
mask: true
})
// 调用平台登录
this.config.platformAdapter.login({
success: (res) => {
if (res.code) {
this._handleAuthRequest(res.code, onSuccess, onError, resolve, reject)
} else {
this._handleAuthError('平台登录失败:' + res.errMsg, onError, reject)
}
},
fail: (error) => {
this._handleAuthError('调用平台登录失败', onError, reject, error)
}
})
})
}
/**
* 处理授权请求
* @private
*/
async _handleAuthRequest(code, onSuccess, onError, resolve, reject) {
try {
// 构建请求数据
const requestData = { code }
// 测试环境下添加测试openid
if (process.env.NODE_ENV === 'development' && this.config.testOpenIds.length > 0) {
requestData.openid = this.config.testOpenIds[0]
}
// 发起授权请求
const response = await this.config.httpAdapter.post(this.config.authUrl, requestData)
this.config.platformAdapter.hideLoading()
if (response.data.code) {
const cookie = response.cookies && response.cookies[0]
if (cookie) {
// 保存sessionid
this.config.storageAdapter.set(this.config.sessionKey, cookie)
// 更新HTTP客户端的默认headers
if (this.config.httpAdapter.updateHeaders) {
this.config.httpAdapter.updateHeaders({ cookie })
}
// 执行成功回调
if (onSuccess) onSuccess(response.data)
if (this.config.onAuthSuccess) this.config.onAuthSuccess(response.data)
resolve(response.data)
} else {
this._handleAuthError('授权失败:没有获取到有效的会话信息', onError, reject)
}
} else {
this._handleAuthError(response.data.msg || '授权失败', onError, reject)
}
} catch (error) {
this.config.platformAdapter.hideLoading()
this._handleAuthError('网络请求失败,请稍后重试', onError, reject, error)
}
}
/**
* 处理授权错误
* @private
*/
_handleAuthError(message, onError, reject, originalError = null) {
console.error('静默授权失败:', message, originalError)
if (onError) onError(message)
if (this.config.onAuthError) this.config.onAuthError(message, originalError)
reject(new Error(message))
}
/**
* 获取当前页面完整路径(包含参数)
* @returns {string} 完整的页面路径
*/
getCurrentPageFullPath() {
return this.config.platformAdapter.getCurrentPageFullPath()
}
/**
* 保存当前页面路径
* @param {string} customPath - 自定义路径
*/
saveCurrentPagePath(customPath) {
const path = customPath || this.getCurrentPageFullPath()
this.config.storageAdapter.set(this.config.routeKey, path)
}
/**
* 跳转到授权页面
* @param {string} returnPath - 授权完成后要返回的页面路径
*/
async navigateToAuth(returnPath) {
// 保存返回路径
if (returnPath) {
this.saveCurrentPagePath(returnPath)
} else {
this.saveCurrentPagePath()
}
// 跳转到授权页面
await this.config.navigatorAdapter.navigateTo({
url: this.config.authPage
})
}
/**
* 授权完成后返回原页面
* @param {string} defaultPath - 默认返回路径
*/
async returnToOriginalPage(defaultPath) {
const finalDefaultPath = defaultPath || this.config.defaultPage
try {
// 获取保存的路径
const savedPath = this.config.storageAdapter.get(this.config.routeKey)
// 清除保存的路径
this.config.storageAdapter.remove(this.config.routeKey)
// 获取当前页面信息
const currentRoute = this.config.platformAdapter.getCurrentRoute()
// 确定目标路径
let targetPath = finalDefaultPath
if (savedPath && savedPath !== '') {
targetPath = savedPath.startsWith('/') ? savedPath : `/${savedPath}`
}
// 如果配置了自定义重定向路径解析函数,使用它来确定最终路径
if (this.config.getRedirectPath) {
targetPath = await this.config.getRedirectPath(savedPath, finalDefaultPath)
}
// 提取目标页面路由(去掉参数)
const targetRoute = targetPath.split('?')[0].replace(/^\//, '')
// 如果当前页面就是目标页面,不需要跳转
if (currentRoute === targetRoute) {
return
}
// 根据目标路径选择跳转方式
if (targetRoute === this.config.defaultPage.replace(/^\//, '')) {
// 如果是默认页面,使用 reLaunch
await this.config.navigatorAdapter.reLaunch({ url: targetPath })
} else {
// 其他页面使用 redirectTo
await this.config.navigatorAdapter.redirectTo({ url: targetPath })
}
} catch (error) {
console.error('returnToOriginalPage 执行出错:', error)
// 错误处理:使用默认路径或自定义错误处理逻辑
try {
let fallbackPath = finalDefaultPath
if (this.config.getRedirectPath) {
fallbackPath = await this.config.getRedirectPath(null, finalDefaultPath)
}
await this.config.navigatorAdapter.reLaunch({ url: fallbackPath })
} catch (finalError) {
console.error('最终降级方案也失败了:', finalError)
}
}
}
/**
* 检查页面是否来自分享
* @param {Object} options - 页面参数
* @returns {boolean} 是否来自分享
*/
isFromShare(options) {
return options && (options.from_share === '1' || options.scene)
}
/**
* 处理分享页面的授权逻辑
* @param {Object} options - 页面参数
* @param {Function} callback - 授权成功后的回调函数
* @returns {boolean} 是否已授权
*/
async handleSharePageAuth(options, callback) {
if (!this.needAuth()) {
// 已授权,执行回调
if (callback && typeof callback === 'function') {
callback()
}
return true
}
// 没有授权,需要先授权
if (this.isFromShare(options)) {
// 来自分享,保存当前页面路径用于授权后返回
this.saveCurrentPagePath()
}
// 跳转到授权页面
await this.navigateToAuth()
return false
}
/**
* 为分享链接添加分享标识参数
* @param {string} path - 原始路径
* @returns {string} 添加分享标识后的路径
*/
addShareFlag(path) {
const separator = path.includes('?') ? '&' : '?'
return `${path}${separator}from_share=1`
}
}
/**
* Taro框架适配器
*/
export class TaroAdapters {
/**
* 存储适配器
*/
static storageAdapter = {
get(key) {
try {
return wx.getStorageSync(key) || null
} catch (error) {
console.error(`获取存储${key}失败:`, error)
return null
}
},
set(key, value) {
try {
wx.setStorageSync(key, value)
} catch (error) {
console.error(`设置存储${key}失败:`, error)
}
},
remove(key) {
try {
wx.removeStorageSync(key)
} catch (error) {
console.error(`删除存储${key}失败:`, error)
}
}
}
/**
* 导航适配器
*/
static navigatorAdapter = {
async navigateTo(options) {
const Taro = await import('@tarojs/taro')
return Taro.default.navigateTo(options)
},
async redirectTo(options) {
const Taro = await import('@tarojs/taro')
return Taro.default.redirectTo(options)
},
async reLaunch(options) {
const Taro = await import('@tarojs/taro')
return Taro.default.reLaunch(options)
}
}
/**
* 平台适配器
*/
static platformAdapter = {
showLoading(options) {
wx.showLoading(options)
},
hideLoading() {
wx.hideLoading()
},
login(options) {
wx.login(options)
},
getCurrentPageFullPath() {
const pages = getCurrentPages()
if (pages.length === 0) return ''
const currentPage = pages[pages.length - 1]
const route = currentPage.route
const options = currentPage.options
// 构建查询参数字符串
const queryParams = Object.keys(options)
.map(key => `${key}=${encodeURIComponent(options[key])}`)
.join('&')
return queryParams ? `${route}?${queryParams}` : route
},
getCurrentRoute() {
const pages = getCurrentPages()
if (pages.length === 0) return ''
const currentPage = pages[pages.length - 1]
return currentPage.route
}
}
/**
* 获取完整的Taro适配器配置
* @param {Object} httpAdapter - HTTP适配器实例
* @returns {Object} 完整的适配器配置
*/
static getAdapters(httpAdapter) {
return {
storageAdapter: this.storageAdapter,
navigatorAdapter: this.navigatorAdapter,
platformAdapter: this.platformAdapter,
httpAdapter: httpAdapter
}
}
}
/**
* 创建老来赛项目的授权管理器实例
* @param {Object} customConfig - 自定义配置
* @returns {UniversalAuthManager} 授权管理器实例
*/
export function createLaolaisaiAuthManager(customConfig = {}) {
// 这里需要传入项目特定的HTTP适配器和业务逻辑
const defaultConfig = {
authPage: '/pages/auth/index',
defaultPage: '/pages/Dashboard/index',
testOpenIds: ['h-008', 'h-009', 'h-010', 'h-011', 'h-012', 'h-013'],
// 这些需要在实际使用时传入
// httpAdapter: request,
// async checkUserStatus() {
// const { code, data } = await getMyFamiliesAPI()
// return code && data && data.length > 0
// },
// async getRedirectPath(savedPath, defaultPath) {
// const hasFamily = await this.checkUserStatus()
// return hasFamily ? (savedPath || defaultPath) : '/pages/Welcome/index'
// }
}
return new UniversalAuthManager({
...defaultConfig,
...customConfig
})
}
export default UniversalAuthManager