sijun.li | 9646230 | 2020-07-24 10:08:05 +0800 | [diff] [blame^] | 1 | import router from './router' |
| 2 | import store from './store' |
| 3 | import { Message } from 'element-ui' |
| 4 | import NProgress from 'nprogress' // progress bar |
| 5 | import 'nprogress/nprogress.css' // progress bar style |
| 6 | import { getToken } from '@/utils/auth' // get token from cookie |
| 7 | import getPageTitle from '@/utils/get-page-title' |
| 8 | |
| 9 | NProgress.configure({ showSpinner: false }) // NProgress Configuration |
| 10 | |
| 11 | const whiteList = ['/login', '/auth-redirect'] // 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() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939 |
| 28 | } else { |
| 29 | // determine whether the user has obtained his permission roles through getInfo |
| 30 | const hasRoles = store.getters.roles && store.getters.roles.length > 0 |
| 31 | if (hasRoles) { |
| 32 | next() |
| 33 | } else { |
| 34 | try { |
| 35 | // get user info |
| 36 | // note: roles must be a object array! such as: ['admin'] or ,['developer','editor'] |
| 37 | const { roles } = await store.dispatch('user/getInfo') |
| 38 | |
| 39 | // generate accessible routes map based on roles |
| 40 | const accessRoutes = await store.dispatch('permission/generateRoutes', roles) |
| 41 | |
| 42 | // dynamically add accessible routes |
| 43 | router.addRoutes(accessRoutes) |
| 44 | |
| 45 | // hack method to ensure that addRoutes is complete |
| 46 | // set the replace: true, so the navigation will not leave a history record |
| 47 | next({ ...to, replace: true }) |
| 48 | } catch (error) { |
| 49 | // remove token and go to login page to re-login |
| 50 | await store.dispatch('user/resetToken') |
| 51 | Message.error(error || 'Has Error') |
| 52 | next(`/login?redirect=${to.path}`) |
| 53 | NProgress.done() |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | } else { |
| 58 | /* has no token*/ |
| 59 | |
| 60 | if (whiteList.indexOf(to.path) !== -1) { |
| 61 | // in the free login whitelist, go directly |
| 62 | next() |
| 63 | } else { |
| 64 | // other pages that do not have permission to access are redirected to the login page. |
| 65 | next(`/login?redirect=${to.path}`) |
| 66 | NProgress.done() |
| 67 | } |
| 68 | } |
| 69 | }) |
| 70 | |
| 71 | router.afterEach(() => { |
| 72 | // finish progress bar |
| 73 | NProgress.done() |
| 74 | }) |