fe-drone-ci/src/permission.js

73 lines
2.7 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
2018-06-07 05:26:10 +00:00
// permission judge function
2017-08-21 07:55:46 +00:00
function hasPermission(roles, permissionRoles) {
if (roles.includes('admin')) return true // admin permission passed directly
2017-08-21 07:55:46 +00:00
if (!permissionRoles) return true
return roles.some(role => permissionRoles.indexOf(role) >= 0)
}
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
2017-11-17 09:51:41 +00:00
2017-08-21 07:55:46 +00:00
router.beforeEach((to, from, next) => {
NProgress.start() // start progress bar
if (getToken()) {
// determine if there has token
2018-01-05 03:38:34 +00:00
/* has token*/
2017-08-21 07:55:46 +00:00
if (to.path === '/login') {
next({ path: '/' })
2018-01-05 03:38:34 +00:00
NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it
2017-08-21 07:55:46 +00:00
} else {
if (store.getters.roles.length === 0) {
// 判断当前用户是否已拉取完user_info信息
store
2019-03-18 10:07:55 +00:00
.dispatch('getInfo') // dispatch @/store/modules/user login getInfo
.then(res => {
// 拉取user_info
2019-03-18 10:07:55 +00:00
const { roles } = res // note: roles must be a object array! such as: [{id: '1', name: 'editor'}, {id: '2', name: 'developer'}]
store.dispatch('generateRoutes', { roles }).then(accessRoutes => {
// 根据roles权限生成可访问的路由表
router.addRoutes(accessRoutes) // 动态添加可访问路由表
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
})
2017-08-21 07:55:46 +00:00
})
.catch(err => {
2019-03-18 10:07:55 +00:00
store.dispatch('resetToken').then(() => {
Message.error(err)
next({ path: '/' })
})
2017-08-21 07:55:46 +00:00
})
} else {
// 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
2018-01-05 03:38:34 +00:00
if (hasPermission(store.getters.roles, to.meta.roles)) {
2018-08-15 09:29:15 +00:00
next()
2017-08-21 07:55:46 +00:00
} else {
2018-01-05 03:38:34 +00:00
next({ path: '/401', replace: true, query: { noGoBack: true }})
2017-08-21 07:55:46 +00:00
}
// 可删 ↑
}
}
} else {
2018-01-05 03:38:34 +00:00
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
// 在免登录白名单,直接进入
2017-08-21 07:55:46 +00:00
next()
} else {
next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
2018-01-05 03:38:34 +00:00
NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
2017-08-21 07:55:46 +00:00
}
}
})
router.afterEach(() => {
NProgress.done() // finish progress bar
2017-08-21 07:55:46 +00:00
})