meituan-beibuwan-h5/util/auth.js

86 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2024-05-30 11:07:45 +08:00
export const authState = {
state: {
phone: undefined,
token: undefined,
},
login(data) {
this.state.phone = data.phone
this.state.token = data.token
localStorage.setItem('auth', JSON.stringify({
"phone": this.state.phone,
"token": this.state.token,
}))
},
logout() {
this.state.phone = undefined
this.state.token = undefined
localStorage.removeItem('auth')
},
isLogin() {
if (this.state.phone == undefined) {
const data = localStorage.getItem("auth")
if (data) {
this.login(JSON.parse(data))
return true
} else {
return false
}
} else {
return true
}
}
}
export const loginPage = "/pages/coupons/index/index";
export const whitelist = [
"pages/coupons/coupon/index",
"/pages/coupons/coupon/index",
"pages/coupons/finish/index",
"/pages/coupons/finish/index",
]
export function checkPage(url = undefined){
if(url == undefined){
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
url = currentPage.route
}
// console.log(url)
if (url != loginPage && whitelist.findIndex((item)=>{return url == item}) == -1 && !authState.isLogin()) {
uni.redirectTo({
url: loginPage
})
uni.showToast({
title: "请登录",
icon: "none"
})
return false
}else return true
}
export function initAuth() {
const routeFnList = ["navigateTo", "redirectTo","reLaunch", "switchTab"]
routeFnList.forEach(item => {
// 添加拦截器
uni.addInterceptor(item, {
invoke(e) {
// 在跳转前做一些事情
return checkPage(e.url)
checkPage(e.url)
},
success(e) {
// 在跳转成功后做一些事情
// console.log('跳转成功', e);
},
fail(e) {
// 在跳转失败后做一些事情
// console.log('跳转失败', e);
},
complete(e) {
// 在跳转结束后做一些事情
// console.log('跳转结束', e);
}
});
})
}