userLoginInfo.ts
1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import type { Router, LocationQueryRaw } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import { useRoute } from 'vue-router';
import { useAppStore, useUserStore } from '@/store';
import {clearToken, isLogin} from '@/utils/auth';
import { WHITE_LIST } from '../constants';
export default function setupUserLoginInfoGuard(router: Router) {
router.beforeEach(async (to, from, next) => {
NProgress.start();
const userStore = useUserStore();
if(to.name == "login"){
clearToken()
}
const route = useRoute();
if (isLogin()) {
if (userStore.roles.length > 0) {
next();
} else {
try {
await userStore.info();
next();
} catch (error) {
await userStore.logout();
next({
name: 'login',
query: {
redirect: to.fullPath,
...to.query,
} as LocationQueryRaw,
});
}
}
} else {
const hasExit = WHITE_LIST.some((item: any) => {
return item.name != 'notFound' && item.name === to.name;
});
if (hasExit) {
next();
return;
}
next({
name: 'login',
query: {
redirect: to.fullPath,
...to.query,
} as LocationQueryRaw,
});
}
});
}