115 lines
2.3 KiB
JavaScript
115 lines
2.3 KiB
JavaScript
import { useAuthStore } from '../store/authStore.js'
|
|
|
|
// 需要登录的页面路径
|
|
const authRequiredPages = [
|
|
'/pages/index/index',
|
|
'/pages/profile/profile',
|
|
'/pages/function/function',
|
|
'/pages/message/message',
|
|
'/pages/tasks/index'
|
|
]
|
|
|
|
// 登录页面路径
|
|
const loginPage = '/pages/login/index'
|
|
|
|
// 首页路径
|
|
const homePage = '/pages/index/index'
|
|
|
|
/**
|
|
* 检查当前页面是否需要登录
|
|
* @param {string} currentPath 当前页面路径
|
|
* @returns {boolean} 是否需要登录
|
|
*/
|
|
export function isAuthRequired(currentPath) {
|
|
return authRequiredPages.includes(currentPath)
|
|
}
|
|
|
|
/**
|
|
* 路由守卫 - 检查登录状态
|
|
* @param {string} toPath 目标页面路径
|
|
* @returns {boolean} 是否允许访问
|
|
*/
|
|
export function checkAuthGuard(toPath) {
|
|
const authStore = useAuthStore()
|
|
|
|
// 如果是登录页面,直接允许访问
|
|
if (toPath === loginPage) {
|
|
return true
|
|
}
|
|
|
|
// 检查是否需要登录
|
|
if (isAuthRequired(toPath)) {
|
|
// 检查是否已登录
|
|
if (!authStore.isAuthenticated) {
|
|
// 跳转到登录页面
|
|
uni.reLaunch({
|
|
url: loginPage
|
|
})
|
|
return false
|
|
}
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
/**
|
|
* 初始化路由守卫
|
|
*/
|
|
export function initRouteGuard() {
|
|
// 监听页面跳转
|
|
uni.addInterceptor('navigateTo', {
|
|
invoke(args) {
|
|
const toPath = args.url.split('?')[0] // 移除查询参数
|
|
if (!checkAuthGuard(toPath)) {
|
|
return false // 阻止跳转
|
|
}
|
|
}
|
|
})
|
|
|
|
uni.addInterceptor('redirectTo', {
|
|
invoke(args) {
|
|
const toPath = args.url.split('?')[0]
|
|
if (!checkAuthGuard(toPath)) {
|
|
return false
|
|
}
|
|
}
|
|
})
|
|
|
|
uni.addInterceptor('switchTab', {
|
|
invoke(args) {
|
|
const toPath = args.url.split('?')[0]
|
|
if (!checkAuthGuard(toPath)) {
|
|
return false
|
|
}
|
|
}
|
|
})
|
|
|
|
uni.addInterceptor('reLaunch', {
|
|
invoke(args) {
|
|
const toPath = args.url.split('?')[0]
|
|
if (!checkAuthGuard(toPath)) {
|
|
return false
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
/**
|
|
* 登录成功后跳转
|
|
* @param {string} redirectPath 重定向路径,默认为首页
|
|
*/
|
|
export function redirectAfterLogin(redirectPath = homePage) {
|
|
uni.reLaunch({
|
|
url: redirectPath
|
|
})
|
|
}
|
|
|
|
/**
|
|
* 登出后跳转
|
|
*/
|
|
export function redirectAfterLogout() {
|
|
uni.reLaunch({
|
|
url: loginPage
|
|
})
|
|
}
|