guards.js
2.5 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
/*
* @Date: 2025-03-20 20:36:36
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-03-26 09:55:40
* @FilePath: /mlaj/src/router/guards.js
* @Description: 路由守卫逻辑
*/
import { getAuthInfoAPI } from '@/api/auth'
import { getUserInfoAPI } from '@/api/users'
import { wxInfo } from "@/utils/tools"
// 需要登录才能访问的路由
export const authRequiredRoutes = [
{
path: '/profile',
exact: false,
},
{
path: '/checkout',
exact: true,
},
{
path: '/activities/[^/]+/signup',
regex: true,
},
]
// 微信授权检查
export const checkWxAuth = async () => {
if (!import.meta.env.DEV && wxInfo().isWeiXin) {
try {
const { code, data } = await getAuthInfoAPI();
if (code && !data.openid_has) {
// 直接在这里处理授权跳转
const params = new URLSearchParams({
f: 'behalo',
a: 'openid',
res: encodeURIComponent(location.origin + location.pathname + location.hash)
});
if (import.meta.env.DEV) {
params.append('test_openid', import.meta.env.VITE_OPENID);
}
location.href = `/srv/?${params.toString()}`;
return false;
}
} catch (error) {
console.error('微信授权检查失败:', error)
}
}
return true
}
// 登录权限检查
export const checkAuth = (to) => {
// TODO: 模拟测试接口
// export const checkAuth = async (to) => {
// try {
// // 先请求用户信息接口
// const { code, data } = await getUserInfoAPI();
// if (code) {
// // 如果成功获取用户信息,更新currentUser并允许访问
// localStorage.setItem('currentUser', JSON.stringify(data));
// return true;
// }
// } catch (error) {
// console.error('获取用户信息失败:', error);
// }
// 如果接口请求失败或返回401,继续原有的本地存储判断逻辑
const currentUser = JSON.parse(localStorage.getItem('currentUser'))
// 检查当前路由是否需要认证
const needAuth = authRequiredRoutes.some((route) => {
// 如果是正则匹配模式
if (route.regex) {
return new RegExp(`^${route.path}$`).test(to.path)
}
// 如果是精确匹配模式
if (route.exact) {
return to.path === route.path
}
// 默认前缀匹配模式
return to.path.startsWith(route.path)
})
if (needAuth && !currentUser) {
// 未登录时重定向到登录页面
return { path: '/login', query: { redirect: to.fullPath } }
}
return true
}