fe-drone-ci/src/permission.js

71 lines
2.2 KiB
JavaScript
Raw Normal View History

2017-08-21 07:55:46 +00:00
import router from './router'
import store from './store'
2018-01-05 03:38:34 +00:00
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
2017-08-21 07:55:46 +00:00
NProgress.configure({ showSpinner: false }) // NProgress Configuration
2018-01-05 03:38:34 +00:00
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
2017-11-17 09:51:41 +00:00
2019-03-21 02:58:44 +00:00
router.beforeEach(async(to, from, next) => {
// start progress bar
NProgress.start()
// determine whether the user has logged in
const hasToken = getToken()
2019-03-21 02:58:44 +00:00
if (hasToken) {
2017-08-21 07:55:46 +00:00
if (to.path === '/login') {
2019-03-21 02:58:44 +00:00
// if is logged in, redirect to the home page
2017-08-21 07:55:46 +00:00
next({ path: '/' })
2019-03-21 02:58:44 +00:00
NProgress.done()
2017-08-21 07:55:46 +00:00
} else {
2019-03-21 02:58:44 +00:00
// determine whether the user has obtained his permission roles through getInfo
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if (hasRoles) {
next()
2017-08-21 07:55:46 +00:00
} else {
2019-03-21 02:58:44 +00:00
try {
// get user info
// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
const { roles } = await store.dispatch('user/getInfo')
// generate accessible routes map based on roles
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
// dynamically add accessible routes
router.addRoutes(accessRoutes)
// hack method to ensure that addRoutes is complete
// set the replace: true, so the navigation will not leave a history record
next({ ...to, replace: true })
} catch (error) {
// remove token and go to login page to re-login
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
NProgress.done()
2017-08-21 07:55:46 +00:00
}
}
}
} else {
2018-01-05 03:38:34 +00:00
/* has no token*/
2019-03-21 02:58:44 +00:00
if (whiteList.indexOf(to.path) !== -1) {
2019-03-21 02:58:44 +00:00
// in the free login whitelist, go directly
2017-08-21 07:55:46 +00:00
next()
} else {
2019-03-21 02:58:44 +00:00
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
NProgress.done()
2017-08-21 07:55:46 +00:00
}
}
})
router.afterEach(() => {
2019-03-21 02:58:44 +00:00
// finish progress bar
NProgress.done()
2017-08-21 07:55:46 +00:00
})