authRedirect.js
4.95 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
import Taro from '@tarojs/taro'
import { routerStore } from '@/stores/router'
import request from '@/utils/request'
export const getCurrentPageFullPath = () => {
const pages = getCurrentPages()
if (!pages || pages.length === 0) return ''
const current_page = pages[pages.length - 1]
const route = current_page.route
const options = current_page.options || {}
const query_params = Object.keys(options)
.map((key) => `${key}=${encodeURIComponent(options[key])}`)
.join('&')
return query_params ? `${route}?${query_params}` : route
}
export const saveCurrentPagePath = (custom_path) => {
const router = routerStore()
const path = custom_path || getCurrentPageFullPath()
router.add(path)
}
export const needAuth = () => {
try {
const sessionid = Taro.getStorageSync('sessionid')
return !sessionid || sessionid === ''
} catch (error) {
console.error('检查授权状态失败:', error)
return true
}
}
export const silentAuth = async (on_success, on_error) => {
try {
if (!needAuth()) {
const result = { code: 1, msg: '已授权' }
if (on_success) on_success(result)
return result
}
Taro.showLoading({
title: '加载中...',
mask: true,
})
const login_result = await new Promise((resolve, reject) => {
Taro.login({
success: resolve,
fail: reject,
})
})
if (!login_result || !login_result.code) {
throw new Error('获取微信登录code失败')
}
const response = await request.post('/srv/?a=openid', {
code: login_result.code,
})
Taro.hideLoading()
if (!response?.data || response.data.code !== 1) {
const error_msg = response?.data?.msg || '授权失败'
if (on_error) on_error(error_msg)
throw new Error(error_msg)
}
let cookie =
(response.cookies && response.cookies[0]) ||
response.header?.['Set-Cookie'] ||
response.header?.['set-cookie']
if (Array.isArray(cookie)) cookie = cookie[0]
if (!cookie) {
const error_msg = '授权失败:没有获取到有效的会话信息'
if (on_error) on_error(error_msg)
throw new Error(error_msg)
}
Taro.setStorageSync('sessionid', cookie)
if (request?.defaults?.headers) {
request.defaults.headers.cookie = cookie
}
if (on_success) on_success(response.data)
return response.data
} catch (error) {
Taro.hideLoading()
const error_msg = error?.message || '授权失败,请稍后重试'
if (on_error) on_error(error_msg)
throw error
}
}
export const navigateToAuth = (return_path) => {
if (return_path) {
saveCurrentPagePath(return_path)
} else {
saveCurrentPagePath()
}
Taro.navigateTo({
url: '/pages/auth/index',
})
}
export const returnToOriginalPage = async (default_path = '/pages/index/index') => {
const router = routerStore()
const saved_path = router.url
try {
router.remove()
const pages = Taro.getCurrentPages()
const current_page = pages[pages.length - 1]
const current_route = current_page?.route
let target_path = default_path
if (saved_path && saved_path !== '') {
target_path = saved_path.startsWith('/') ? saved_path : `/${saved_path}`
}
const target_route = target_path.split('?')[0].replace(/^\//, '')
if (current_route === target_route) {
return
}
try {
await Taro.redirectTo({ url: target_path })
} catch (error) {
await Taro.reLaunch({ url: target_path })
}
} catch (error) {
console.error('returnToOriginalPage 执行出错:', error)
try {
await Taro.reLaunch({ url: default_path })
} catch (final_error) {
console.error('最终降级方案也失败了:', final_error)
}
}
}
export const isFromShare = (options) => {
return options && (options.from_share === '1' || options.scene)
}
export const handleSharePageAuth = async (options, callback) => {
if (!needAuth()) {
if (typeof callback === 'function') callback()
return true
}
if (isFromShare(options)) {
saveCurrentPagePath()
}
try {
await silentAuth(
() => {
if (typeof callback === 'function') callback()
},
() => {
Taro.navigateTo({ url: '/pages/auth/index' })
}
)
return true
} catch (error) {
Taro.navigateTo({ url: '/pages/auth/index' })
return false
}
}
export const addShareFlag = (path) => {
const separator = path.includes('?') ? '&' : '?'
return `${path}${separator}from_share=1`
}