提交 | 用户 | age
|
2a61f6
|
1 |
import router from './router' |
L |
2 |
import { Message } from 'element-ui' |
|
3 |
import Req from './utils/http_install' |
|
4 |
import NProgress from 'nprogress' // progress bar |
|
5 |
import 'nprogress/nprogress.css' // progress bar style |
|
6 |
import { getToken, getUserData, removeToken, removeUserData } from '@/utils/auth' // get token from session |
|
7 |
import getPageTitle from '@/utils/get-page-title' |
|
8 |
|
|
9 |
NProgress.configure({ showSpinner: false }) // NProgress Configuration |
|
10 |
|
|
11 |
const whiteList = ['/login'] // no redirect whitelist |
|
12 |
|
|
13 |
router.beforeEach(async(to, from, next) => { |
|
14 |
// start progress bar |
|
15 |
NProgress.start() |
|
16 |
|
|
17 |
// set page title |
|
18 |
document.title = getPageTitle(to.meta.title) |
|
19 |
|
|
20 |
// determine whether the user has logged in |
|
21 |
const hasToken = getToken() |
|
22 |
|
|
23 |
if (hasToken) { |
|
24 |
if (to.path === '/login') { |
|
25 |
// if is logged in, redirect to the home page |
|
26 |
next({ path: '/' }) |
|
27 |
NProgress.done() |
|
28 |
} else { |
|
29 |
const hasGetUserInfo = getUserData() |
|
30 |
if (hasGetUserInfo) { |
|
31 |
next() |
|
32 |
} else { |
|
33 |
Req.http.postFN({ |
|
34 |
url: 'admin/logout', |
|
35 |
udData: { noToken: true }, |
|
36 |
mockData: { |
|
37 |
code: 100, |
|
38 |
msg: '', |
|
39 |
data: {} |
|
40 |
} |
|
41 |
}, () => { |
|
42 |
Message.error('登录失效,重新登录') |
|
43 |
removeToken() // 清除token |
|
44 |
removeUserData() // 清除userData |
|
45 |
next(`/login?redirect=${to.path}`) |
|
46 |
NProgress.done() |
|
47 |
}) |
|
48 |
} |
|
49 |
} |
|
50 |
} else { |
|
51 |
/* has no token*/ |
|
52 |
|
|
53 |
if (whiteList.indexOf(to.path) !== -1) { |
|
54 |
// in the free login whitelist, go directly |
|
55 |
next() |
|
56 |
} else { |
|
57 |
// other pages that do not have permission to access are redirected to the login page. |
|
58 |
next(`/login?redirect=${to.path}`) |
|
59 |
NProgress.done() |
|
60 |
} |
|
61 |
} |
|
62 |
}) |
|
63 |
|
|
64 |
router.afterEach(() => { |
|
65 |
// finish progress bar |
|
66 |
NProgress.done() |
|
67 |
}) |