vending-machine/mobile/utils/auth.js
2026-04-08 20:45:41 +08:00

68 lines
1.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { getStorage, TOKEN_KEY } from './storage.js'
// 需要登录才能访问的页面路径列表
const AUTH_PAGES = [
'/pages/mine/mine',
'/pages/points/points',
'/pages/coupons/coupons',
'/pages/about/about'
]
/**
* 检查页面是否需要登录
* @param {string} pagePath - 页面路径
* @returns {boolean}
*/
export function isAuthRequired(pagePath) {
// 统一格式:确保以 / 开头
const path = pagePath.startsWith('/') ? pagePath : `/${pagePath}`
return AUTH_PAGES.some(p => path.startsWith(p))
}
/**
* 检查用户是否已登录
* @returns {boolean}
*/
export function isAuthenticated() {
return !!getStorage(TOKEN_KEY)
}
/**
* 路由守卫:检查目标页面是否需要登录,未登录则跳转登录页
* @param {string} pagePath - 目标页面路径
* @returns {boolean} true表示允许访问false表示已拦截跳转登录页
*/
export function checkAuth(pagePath) {
if (isAuthRequired(pagePath) && !isAuthenticated()) {
uni.navigateTo({ url: '/pages/login/login' })
return false
}
return true
}
/**
* 初始化应用状态在App.vue onLaunch中调用
* - 初始化语言设置
* - 如果已登录则获取用户信息
*/
export async function initAppState() {
const { useAppStore } = await import('../stores/app.js')
const { useUserStore } = await import('../stores/user.js')
const appStore = useAppStore()
const userStore = useUserStore()
// 初始化语言
appStore.initLocale()
// 如果有Token尝试获取用户信息
if (userStore.isLoggedIn) {
try {
await userStore.fetchUserInfo()
} catch (e) {
// 获取失败如Token过期由请求拦截器处理401
console.warn('初始化用户信息失败:', e.message)
}
}
}