refactor permission

This commit is contained in:
Pan 2019-03-21 10:58:44 +08:00
parent e1d61898ed
commit 0c6e45e9a1
6 changed files with 83 additions and 71 deletions

View File

@ -79,8 +79,7 @@ export default {
}, },
async logout() { async logout() {
await this.$store.dispatch('user/logout') await this.$store.dispatch('user/logout')
// In order to re-instantiate the vue-router object to avoid bugs this.$router.push(`/login?redirect=${this.$route.fullPath}`)
location.reload()
} }
} }
} }

View File

@ -7,66 +7,64 @@ import { getToken } from '@/utils/auth' // get token from cookie
NProgress.configure({ showSpinner: false }) // NProgress Configuration NProgress.configure({ showSpinner: false }) // NProgress Configuration
// permission judge function
function hasPermission(roles, permissionRoles) {
if (roles.includes('admin')) return true // admin permission passed directly
if (!permissionRoles) return true
return roles.some(role => permissionRoles.indexOf(role) >= 0)
}
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
router.beforeEach((to, from, next) => { router.beforeEach(async(to, from, next) => {
NProgress.start() // start progress bar // start progress bar
if (getToken()) { NProgress.start()
// determine if there has token
/* has token*/ // determine whether the user has logged in
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') { if (to.path === '/login') {
// if is logged in, redirect to the home page
next({ path: '/' }) next({ path: '/' })
NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it NProgress.done()
} else { } else {
if (store.getters.roles.length === 0) { // determine whether the user has obtained his permission roles through getInfo
// 判断当前用户是否已拉取完user_info信息 const hasRoles = store.getters.roles && store.getters.roles.length > 0
store if (hasRoles) {
.dispatch('user/getInfo') next()
.then(res => {
// 拉取user_info
const { roles } = res // note: roles must be a object array! such as: [{id: '1', name: 'editor'}, {id: '2', name: 'developer'}]
store.dispatch('permission/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
})
})
.catch(err => {
store.dispatch('user/resetToken').then(() => {
Message.error(err)
next({ path: '/' })
})
})
} else { } else {
// 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓ try {
if (hasPermission(store.getters.roles, to.meta.roles)) { // get user info
next() // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
} else { const { roles } = await store.dispatch('user/getInfo')
next({ path: '/401', replace: true, query: { noGoBack: true }})
// 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()
} }
// 可删 ↑
} }
} }
} else { } else {
/* has no token*/ /* has no token*/
if (whiteList.indexOf(to.path) !== -1) { if (whiteList.indexOf(to.path) !== -1) {
// 在免登录白名单,直接进入 // in the free login whitelist, go directly
next() next()
} else { } else {
next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页 // other pages that do not have permission to access are redirected to the login page.
NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it next(`/login?redirect=${to.path}`)
NProgress.done()
} }
} }
}) })
router.afterEach(() => { router.afterEach(() => {
NProgress.done() // finish progress bar // finish progress bar
NProgress.done()
}) })

View File

@ -105,12 +105,6 @@ export const constantRoutes = [
} }
] ]
export default new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes
})
export const asyncRoutes = [ export const asyncRoutes = [
{ {
path: '/permission', path: '/permission',
@ -383,3 +377,19 @@ export const asyncRoutes = [
{ path: '*', redirect: '/404', hidden: true } { path: '*', redirect: '/404', hidden: true }
] ]
const createRouter = () => new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes
})
const router = createRouter()
// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}
export default router

View File

@ -47,9 +47,8 @@ const mutations = {
} }
const actions = { const actions = {
generateRoutes({ commit }, data) { generateRoutes({ commit }, roles) {
return new Promise(resolve => { return new Promise(resolve => {
const { roles } = data
let accessedRoutes let accessedRoutes
if (roles.includes('admin')) { if (roles.includes('admin')) {
accessedRoutes = asyncRoutes accessedRoutes = asyncRoutes

View File

@ -1,5 +1,6 @@
import { login, logout, getInfo } from '@/api/user' import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth' import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
const state = { const state = {
token: getToken(), token: getToken(),
@ -78,6 +79,7 @@ const actions = {
commit('SET_TOKEN', '') commit('SET_TOKEN', '')
commit('SET_ROLES', []) commit('SET_ROLES', [])
removeToken() removeToken()
resetRouter()
resolve() resolve()
}).catch(error => { }).catch(error => {
reject(error) reject(error)
@ -95,22 +97,25 @@ const actions = {
}) })
}, },
// 动态修改权限 // Dynamically modify permissions
changeRoles({ commit, dispatch }, role) { changeRoles({ commit, dispatch }, role) {
return new Promise(resolve => { return new Promise(async resolve => {
const token = role + '-token' const token = role + '-token'
commit('SET_TOKEN', token) commit('SET_TOKEN', token)
setToken(token) setToken(token)
getInfo(token).then(response => {
const { data } = response const { roles } = await dispatch('getInfo')
const { roles, name, avatar, introduction } = data
commit('SET_ROLES', roles) resetRouter()
commit('SET_NAME', name)
commit('SET_AVATAR', avatar) // generate accessible routes map based on roles
commit('SET_INTRODUCTION', introduction) const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
dispatch('permission/generateRoutes', data) // 动态修改权限后 重绘侧边菜单
resolve() // dynamically add accessible routes
}) router.addRoutes(accessRoutes)
resolve()
}) })
} }
} }

View File

@ -135,13 +135,14 @@ export default {
this.$refs.loginForm.validate(valid => { this.$refs.loginForm.validate(valid => {
if (valid) { if (valid) {
this.loading = true this.loading = true
// dispatch @/store/modules/user login action this.$store.dispatch('user/login', this.loginForm)
this.$store.dispatch('user/login', this.loginForm).then(() => { .then(() => {
this.loading = false this.$router.push({ path: this.redirect || '/' })
this.$router.push({ path: this.redirect || '/' }) this.loading = false
}).catch(() => { })
this.loading = false .catch(() => {
}) this.loading = false
})
} else { } else {
console.log('error submit!!') console.log('error submit!!')
return false return false