lg_frontend/middleware/auth.js

47 lines
1.4 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.

// 在某个适当的时间点检查登录状态是否过期
function isLoginExpired(loginTimestamp, expirationDuration) {
// 获取登录时间戳
// 如果没有登录时间戳,说明用户未登录或状态已过期
if (!loginTimestamp) {
return true;
}
// 计算登录时间和现在的时间差
const currentTimestamp = Date.now();
const duration = currentTimestamp - loginTimestamp;
// 如果时间差大于3小时的毫秒数则登录状态过期
return duration > expirationDuration;
}
export default function ({ route, redirect, store }) {
if (route.name === 'manager-login') {
return
}
if (localStorage.getItem('userInfo')) {
const cache = JSON.parse(localStorage.getItem('userInfo'))
const { expire, loginTime } = cache
// 在页面加载时检查登录状态
if (isLoginExpired(loginTime, expire)) {
// 用户登录已过期,执行登录过期的逻辑
console.log('登录已过期');
return redirect('/manager/login')
} else {
// 用户登录有效,执行登录有效的逻辑
store.dispatch('user/setUserInfo', cache)
if (route.path === '/') {
return redirect('/home')
}
}
} else {
// 假设用户信息存储在 Vuex store 中
const user = store.state.user
// 检查路由是否需要认证
if (!user.isLogin) {
return redirect('/manager/login')
}
}
}