guards.js
1.59 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
/*
* @Date: 2025-03-20 20:36:36
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-03-25 15:17:18
* @FilePath: /mlaj/src/router/guards.js
* @Description: 路由守卫逻辑
*/
import { getAuthInfoAPI } from '@/api/auth'
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 (to) => {
if (!import.meta.env.DEV && wxInfo().isWeiXin && to.path !== '/auth') {
try {
const { code, data } = await getAuthInfoAPI();
if (code && !data.openid_has) {
return { path: '/auth', query: { href: location.hash } }
}
} catch (error) {
console.error('微信授权检查失败:', error)
}
}
return true
}
// 登录权限检查
export const checkAuth = (to) => {
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
}