refactor: router guard
This commit is contained in:
@@ -49,22 +49,34 @@ const router = createRouter({
|
||||
],
|
||||
});
|
||||
|
||||
const whiteList = ['/login', '/debug'];
|
||||
const whiteList = ['/debug'];
|
||||
|
||||
router.beforeEach((to, from, next) => {
|
||||
const userStore = useUserStore();
|
||||
if (userStore.userLoginResult?.token) {
|
||||
if (to.path === '/login') {
|
||||
const isAuthed = !!userStore.userLoginResult?.token;
|
||||
|
||||
// 放行白名单
|
||||
const inWhiteList = whiteList.some((path) => to.path.startsWith(path));
|
||||
if (inWhiteList) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
// 已登录用户不允许进入登录页(手动访问 /login 会重定向到首页)
|
||||
if (to.path === '/login') {
|
||||
if (isAuthed) {
|
||||
next({ path: '/' });
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 其它路由按登录态控制
|
||||
if (!isAuthed) {
|
||||
next('/login');
|
||||
} else {
|
||||
if (whiteList.includes(to.path)) {
|
||||
next();
|
||||
} else {
|
||||
next('/login');
|
||||
}
|
||||
next();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user