Files
cz-app/src/utils/auth-guard.ts
2026-09-21 15:41:52 +08:00

42 lines
956 B
TypeScript
Raw 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 { clearAuthSession, getAccessToken } from '@/utils/auth-storage'
export const LOGIN_PAGE = '/pages/Login/user-login/index'
let redirectingToLogin = false
export function isLoggedIn() {
return Boolean(getAccessToken())
}
/** 未登录时跳转登录页,返回是否已登录 */
export function ensureLoggedIn(showToast = true) {
if (isLoggedIn())
return true
if (showToast)
uni.showToast({ title: '请先登录', icon: 'none' })
redirectToLogin()
return false
}
/** 登录态失效(如接口返回 401)时清除会话并跳转登录页 */
export function handleUnauthorized(message = '登录已过期,请重新登录') {
if (redirectingToLogin)
return
redirectingToLogin = true
clearAuthSession()
uni.showToast({ title: message, icon: 'none' })
redirectToLogin()
}
function redirectToLogin() {
uni.reLaunch({
url: LOGIN_PAGE,
complete: () => {
redirectingToLogin = false
},
})
}