diff --git a/mock/mocks.js b/mock/mocks.js index 9e551722..f1c41ab5 100644 --- a/mock/mocks.js +++ b/mock/mocks.js @@ -2,11 +2,13 @@ import login from './login' import article from './article' import search from './remoteSearch' import transaction from './transaction' +import role from './role' export default { ...login, ...article, ...search, - ...transaction + ...transaction, + ...role } diff --git a/mock/role/index.js b/mock/role/index.js new file mode 100644 index 00000000..cc055f8d --- /dev/null +++ b/mock/role/index.js @@ -0,0 +1,61 @@ +import Mock from 'mockjs' +// import { deepClone } from '@/utils' +// import { filterAsyncRoutes } from '@/store/modules/permission' +// import { asyncRoutes, constantRoutes } from '@/router' + +// const routes = deepClone([...constantRoutes, ...asyncRoutes]) + +const roles = [ + { + key: 'admin', + name: 'admin', + description: 'Super Administrator. Have access to view all pages.', + routes: [] + }, + { + key: 'editor', + name: 'editor', + description: 'Normal Editor. Can see all pages except permission page', + routes: [] + }, + { + key: 'visitor', + name: 'visitor', + description: 'Just a visitor. Can only see the home page and the document page', + routes: [{ + path: '', + redirect: 'dashboard', + children: [ + { + path: 'dashboard', + name: 'Dashboard', + meta: { title: 'dashboard', icon: 'dashboard' } + } + ] + }] + } +] + +export default { + '/routes': () => { + return [] + }, + '/roles': () => { + return roles + }, + '/roles/add': () => { + return Mock.mock('@integer(300, 5000)') + }, + '/roles/update/\/[A-Za-z0-9]': () => { + const res = { + data: 'success' + } + return res + }, + '/roles/delete/\/[A-Za-z0-9]'() { + const res = { + data: 'success' + } + return res + } +} diff --git a/src/api/role.js b/src/api/role.js new file mode 100644 index 00000000..1d6da8b3 --- /dev/null +++ b/src/api/role.js @@ -0,0 +1,38 @@ +import request from '@/utils/request' + +export function getRoutes() { + return request({ + url: '/routes', + method: 'get' + }) +} + +export function getRoles() { + return request({ + url: '/roles', + method: 'get' + }) +} + +export function addRole(data) { + return request({ + url: '/roles/add', + method: 'post', + data + }) +} + +export function updateRole(id, data) { + return request({ + url: `/roles/update/${id}`, + method: 'put', + data + }) +} + +export function deleteRole(id) { + return request({ + url: `/roles/delete/${id}`, + method: 'delete' + }) +} diff --git a/src/components/HeaderSearch/index.vue b/src/components/HeaderSearch/index.vue index f3adb327..7f8fdc4c 100644 --- a/src/components/HeaderSearch/index.vue +++ b/src/components/HeaderSearch/index.vue @@ -36,8 +36,8 @@ export default { } }, computed: { - routers() { - return this.$store.getters.permission_routers + routes() { + return this.$store.getters.permission_routes }, lang() { return this.$store.getters.language @@ -45,10 +45,10 @@ export default { }, watch: { lang() { - this.searchPool = this.generateRouters(this.routers) + this.searchPool = this.generateRoutes(this.routes) }, - routers() { - this.searchPool = this.generateRouters(this.routers) + routes() { + this.searchPool = this.generateRoutes(this.routes) }, searchPool(list) { this.initFuse(list) @@ -62,7 +62,7 @@ export default { } }, mounted() { - this.searchPool = this.generateRouters(this.routers) + this.searchPool = this.generateRoutes(this.routes) }, methods: { click() { @@ -103,10 +103,10 @@ export default { }, // Filter out the routes that can be displayed in the sidebar // And generate the internationalized title - generateRouters(routers, basePath = '/', prefixTitle = []) { + generateRoutes(routes, basePath = '/', prefixTitle = []) { let res = [] - for (const router of routers) { + for (const router of routes) { // skip hidden router if (router.hidden) { continue } @@ -128,11 +128,11 @@ export default { } } - // recursive child routers + // recursive child routes if (router.children) { - const tempRouters = this.generateRouters(router.children, data.path, data.title) - if (tempRouters.length >= 1) { - res = [...res, ...tempRouters] + const tempRoutes = this.generateRoutes(router.children, data.path, data.title) + if (tempRoutes.length >= 1) { + res = [...res, ...tempRoutes] } } } diff --git a/src/lang/en.js b/src/lang/en.js index 05b34598..caed5c5b 100644 --- a/src/lang/en.js +++ b/src/lang/en.js @@ -6,6 +6,7 @@ export default { guide: 'Guide', permission: 'Permission', pagePermission: 'Page Permission', + rolePermission: 'Role Permission', directivePermission: 'Directive Permission', icons: 'Icons', components: 'Components', @@ -86,9 +87,14 @@ export default { github: 'Github Repository' }, permission: { + addRole: 'New Role', + editPermission: 'Edit Permission', roles: 'Your roles', switchRoles: 'Switch roles', - tips: 'In some cases it is not suitable to use v-permission, such as element Tab component or el-table-column and other asynchronous rendering dom cases which can only be achieved by manually setting the v-if.' + tips: 'In some cases it is not suitable to use v-permission, such as element Tab component or el-table-column and other asynchronous rendering dom cases which can only be achieved by manually setting the v-if.', + delete: 'Delete', + confirm: 'Confirm', + cancel: 'Cancel' }, guide: { description: 'The guide page is useful for some people who entered the project for the first time. You can briefly introduce the features of the project. Demo is based on ', diff --git a/src/lang/es.js b/src/lang/es.js index 8575d382..f0d7de41 100755 --- a/src/lang/es.js +++ b/src/lang/es.js @@ -5,6 +5,7 @@ export default { documentation: 'Documentación', guide: 'Guía', permission: 'Permisos', + rolePermission: 'Permisos de rol', pagePermission: 'Permisos de la página', directivePermission: 'Permisos de la directiva', icons: 'Iconos', @@ -86,9 +87,14 @@ export default { github: 'Repositorio Github' }, permission: { + addRole: 'Nuevo rol', + editPermission: 'Permiso de edición', roles: 'Tus permisos', switchRoles: 'Cambiar permisos', - tips: 'In some cases it is not suitable to use v-permission, such as element Tab component or el-table-column and other asynchronous rendering dom cases which can only be achieved by manually setting the v-if.' + tips: 'In some cases it is not suitable to use v-permission, such as element Tab component or el-table-column and other asynchronous rendering dom cases which can only be achieved by manually setting the v-if.', + delete: 'Borrar', + confirm: 'Confirmar', + cancel: 'Cancelar' }, guide: { description: 'The guide page is useful for some people who entered the project for the first time. You can briefly introduce the features of the project. Demo is based on ', diff --git a/src/lang/zh.js b/src/lang/zh.js index 1fd18355..9bea838e 100644 --- a/src/lang/zh.js +++ b/src/lang/zh.js @@ -5,6 +5,7 @@ export default { documentation: '文档', guide: '引导页', permission: '权限测试页', + rolePermission: '角色权限', pagePermission: '页面权限', directivePermission: '指令权限', icons: '图标', @@ -86,9 +87,14 @@ export default { github: 'Github 地址' }, permission: { + addRole: '新增角色', + editPermission: '编辑权限', roles: '你的权限', switchRoles: '切换权限', - tips: '在某些情况下,不适合使用 v-permission。例如:Element-UI 的 Tab 组件或 el-table-column 以及其它动态渲染 dom 的场景。你只能通过手动设置 v-if 来实现。' + tips: '在某些情况下,不适合使用 v-permission。例如:Element-UI 的 Tab 组件或 el-table-column 以及其它动态渲染 dom 的场景。你只能通过手动设置 v-if 来实现。', + delete: '删除', + confirm: '确定', + cancel: '取消' }, guide: { description: '引导页对于一些第一次进入项目的人很有用,你可以简单介绍下项目的功能。本 Demo 是基于', diff --git a/src/layout/components/Sidebar/index.vue b/src/layout/components/Sidebar/index.vue index 4c37b501..4c4d6db4 100644 --- a/src/layout/components/Sidebar/index.vue +++ b/src/layout/components/Sidebar/index.vue @@ -9,7 +9,7 @@ :collapse-transition="false" mode="vertical" > - + @@ -23,7 +23,7 @@ export default { components: { SidebarItem }, computed: { ...mapGetters([ - 'permission_routers', + 'permission_routes', 'sidebar' ]), variables() { diff --git a/src/layout/components/TagsView/index.vue b/src/layout/components/TagsView/index.vue index 80ca52a0..6b63d765 100644 --- a/src/layout/components/TagsView/index.vue +++ b/src/layout/components/TagsView/index.vue @@ -54,8 +54,8 @@ export default { visitedViews() { return this.$store.state.tagsView.visitedViews }, - routers() { - return this.$store.state.permission.routers + routes() { + return this.$store.state.permission.routes } }, watch: { @@ -102,7 +102,7 @@ export default { return tags }, initTags() { - const affixTags = this.affixTags = this.filterAffixTags(this.routers) + const affixTags = this.affixTags = this.filterAffixTags(this.routes) for (const tag of affixTags) { // Must have tag name if (tag.name) { diff --git a/src/permission.js b/src/permission.js index e556cb00..25b6812f 100644 --- a/src/permission.js +++ b/src/permission.js @@ -2,41 +2,49 @@ import router from './router' import store from './store' import { Message } from 'element-ui' import NProgress from 'nprogress' // progress bar -import 'nprogress/nprogress.css'// progress bar style -import { getToken } from '@/utils/auth' // getToken from cookie +import 'nprogress/nprogress.css' // progress bar style +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.indexOf('admin') >= 0) return true // admin permission passed directly + 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) => { NProgress.start() // start progress bar - if (getToken()) { // determine if there has token + if (getToken()) { + // determine if there has token + /* has token*/ if (to.path === '/login') { next({ path: '/' }) NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it } else { - if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息 - store.dispatch('GetUserInfo').then(res => { // 拉取user_info - const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop'] - store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表 - router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表 - next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record + if (store.getters.roles.length === 0) { + // 判断当前用户是否已拉取完user_info信息 + store + .dispatch('GetUserInfo') + .then(res => { + // 拉取user_info + const roles = res.data.roles // 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 + }) }) - }).catch((err) => { - store.dispatch('FedLogOut').then(() => { - Message.error(err) - next({ path: '/' }) + .catch(err => { + store.dispatch('FedLogOut').then(() => { + Message.error(err) + next({ path: '/' }) + }) }) - }) } else { // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓ if (hasPermission(store.getters.roles, to.meta.roles)) { @@ -49,7 +57,8 @@ router.beforeEach((to, from, next) => { } } else { /* has no token*/ - if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入 + if (whiteList.indexOf(to.path) !== -1) { + // 在免登录白名单,直接进入 next() } else { next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页 diff --git a/src/router/index.js b/src/router/index.js index 39abc114..529c1ab2 100644 --- a/src/router/index.js +++ b/src/router/index.js @@ -33,7 +33,7 @@ import nestedRouter from './modules/nested' affix: true if true, the tag will affix in the tags-view } **/ -export const constantRouterMap = [ +export const constantRoutes = [ { path: '/redirect', component: Layout, @@ -81,7 +81,6 @@ export const constantRouterMap = [ { path: '/documentation', component: Layout, - redirect: '/documentation/index', children: [ { path: 'index', @@ -109,10 +108,10 @@ export const constantRouterMap = [ export default new Router({ // mode: 'history', // require service support scrollBehavior: () => ({ y: 0 }), - routes: constantRouterMap + routes: constantRoutes }) -export const asyncRouterMap = [ +export const asyncRoutes = [ { path: '/permission', component: Layout, @@ -141,6 +140,15 @@ export const asyncRouterMap = [ title: 'directivePermission' // if do not set roles, means: this page does not require permission } + }, + { + path: 'role', + component: () => import('@/views/permission/role'), + name: 'RolePermission', + meta: { + title: 'rolePermission', + roles: ['admin'] + } } ] }, diff --git a/src/store/getters.js b/src/store/getters.js index cf314f5c..797573f7 100644 --- a/src/store/getters.js +++ b/src/store/getters.js @@ -12,8 +12,8 @@ const getters = { status: state => state.user.status, roles: state => state.user.roles, setting: state => state.user.setting, - permission_routers: state => state.permission.routers, - addRouters: state => state.permission.addRouters, + permission_routes: state => state.permission.routes, + addRoutes: state => state.permission.addRoutes, errorLogs: state => state.errorLog.logs } export default getters diff --git a/src/views/permission/role.vue b/src/views/permission/role.vue new file mode 100644 index 00000000..4d7fa8be --- /dev/null +++ b/src/views/permission/role.vue @@ -0,0 +1,283 @@ + + + + + diff --git a/vue.config.js b/vue.config.js index f77d6598..da85498d 100644 --- a/vue.config.js +++ b/vue.config.js @@ -1,7 +1,8 @@ 'use strict' require('@babel/register') +require('module-alias/register') const path = require('path') -const settings = require('./src/settings.js').default +const { default: settings } = require('./src/settings.js') const { name } = settings function resolve(dir) { @@ -54,6 +55,7 @@ module.exports = { // import ES2015 module from common.js module const { default: mocks } = require('./mock') for (const mock of mocks) { + console.log(mock, mock.response) app.all(mock.route, mock.response) } }