144 lines
2.6 KiB
JavaScript
144 lines
2.6 KiB
JavaScript
import config from '@/config/index.js'
|
|
|
|
// 全局存储当前路由
|
|
let currentRoute = ''
|
|
|
|
/**
|
|
* 设置当前路由
|
|
* @param {string} route
|
|
*/
|
|
export function setCurrentRoute(route) {
|
|
currentRoute = route
|
|
}
|
|
|
|
/**
|
|
* 检查是否已登录
|
|
* @returns {boolean}
|
|
*/
|
|
export function isLogin() {
|
|
try {
|
|
const token = uni.getStorageSync('token')
|
|
return !!token
|
|
} catch (e) {
|
|
console.error('检查登录状态失败:', e)
|
|
return false
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取当前页面路径
|
|
* @returns {string}
|
|
*/
|
|
export function getCurrentRoute() {
|
|
try {
|
|
// 如果有存储的路由,优先使用
|
|
if (currentRoute) {
|
|
return currentRoute
|
|
}
|
|
|
|
const pages = getCurrentPages()
|
|
if (pages && pages.length > 0) {
|
|
const currentPage = pages[pages.length - 1]
|
|
const route = currentPage ? `/${currentPage.route}` : ''
|
|
currentRoute = route
|
|
return route
|
|
}
|
|
|
|
return ''
|
|
} catch (e) {
|
|
console.error('获取当前路由失败:', e)
|
|
return ''
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 检查当前路由是否在白名单中
|
|
* @returns {boolean}
|
|
*/
|
|
export function isInWhitelist(route) {
|
|
try {
|
|
const currentRoute = route || getCurrentRoute()
|
|
if (!currentRoute) return false
|
|
|
|
return config.whitelist.some(path => currentRoute.includes(path))
|
|
} catch (e) {
|
|
console.error('检查白名单失败:', e)
|
|
return false
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 检查登录状态,未登录则跳转到登录页
|
|
* @returns {boolean} 是否已登录
|
|
*/
|
|
export function checkLogin() {
|
|
try {
|
|
const currentRoute = getCurrentRoute()
|
|
|
|
// 如果当前路由为空,可能是页面刚初始化,暂不检查
|
|
if (!currentRoute) {
|
|
return true
|
|
}
|
|
|
|
// 如果在白名单中,不检查登录状态
|
|
if (isInWhitelist(currentRoute)) {
|
|
return true
|
|
}
|
|
|
|
// 检查是否已登录
|
|
if (isLogin()) {
|
|
return true
|
|
}
|
|
|
|
// 未登录,跳转到登录页
|
|
if (currentRoute !== '/pages/ucenter/login/index') {
|
|
uni.showToast({
|
|
title: '请先登录',
|
|
icon: 'none',
|
|
duration: 2000
|
|
})
|
|
|
|
setTimeout(() => {
|
|
uni.reLaunch({
|
|
url: '/pages/ucenter/login/index',
|
|
fail: (err) => {
|
|
console.error('跳转登录页失败:', err)
|
|
}
|
|
})
|
|
}, 1500)
|
|
}
|
|
|
|
return false
|
|
} catch (e) {
|
|
console.error('检查登录失败:', e)
|
|
return false
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 退出登录
|
|
*/
|
|
export function logout() {
|
|
try {
|
|
uni.removeStorageSync('token')
|
|
uni.removeStorageSync('userInfo')
|
|
|
|
uni.showToast({
|
|
title: '已退出登录',
|
|
icon: 'success',
|
|
duration: 1500
|
|
})
|
|
|
|
setTimeout(() => {
|
|
uni.reLaunch({
|
|
url: '/pages/ucenter/login/index',
|
|
fail: (err) => {
|
|
console.error('跳转登录页失败:', err)
|
|
}
|
|
})
|
|
}, 1500)
|
|
} catch (e) {
|
|
console.error('退出登录失败:', e)
|
|
}
|
|
}
|