mirror of
https://github.com/PanJiaChen/vue-element-admin.git
synced 2026-11-17 15:13:37 +08:00
Merge a1c452fd32b549c905d36ab4815759d8757e7152 into 6858a9ad67483025f6a9432a926beb9327037be3
This commit is contained in:
commit
2bf3f4685e
29
docs/server-permissions.md
Normal file
29
docs/server-permissions.md
Normal file
@ -0,0 +1,29 @@
|
||||
# Server-driven route permissions
|
||||
|
||||
Set `permissionMode: 'server'` in `src/settings.js`, then run the usual development server. Sign in as `admin`, open **Permission → Role Permission**, edit the editor's menu tree, and save. Switch to editor on the Page Permission demo (or log out and sign in as editor). Its sidebar and reachable dynamic routes now come from the saved server response. Nested menus can be selected at any depth. Public login, dashboard, documentation, and error pages remain local.
|
||||
|
||||
The default `frontend` mode preserves the existing local `meta.roles` filtering. Server mode calls `GET /vue-element-admin/user/routes` on initial login and when the demo switches roles. It does not grant every local route to an admin role: the server's returned tree is authoritative for every user. A failed request or unknown component rejects route generation instead of falling back to local permissions.
|
||||
|
||||
The endpoint returns `{ code: 20000, data: [...] }`. Each node uses the usual route fields (`path`, `name`, `redirect`, `hidden`, `alwaysShow`, `meta`, and `children`) but represents its component with a string, for example:
|
||||
|
||||
```json
|
||||
{
|
||||
"path": "/nested",
|
||||
"component": "layout/Layout",
|
||||
"name": "Nested",
|
||||
"alwaysShow": true,
|
||||
"meta": { "title": "Nested Routes", "icon": "nested" },
|
||||
"children": [{
|
||||
"path": "menu2",
|
||||
"component": "views/nested/menu2/index",
|
||||
"name": "Menu2",
|
||||
"meta": { "title": "Menu 2" }
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Only `Layout`/`layout/Layout` and Vue files bundled under `src/views` are resolved. Directory names resolve their `index.vue`; `.vue` names omit the extension. The client does not evaluate server code or load remote components. The returned tree must exclude the locally registered constant routes.
|
||||
|
||||
The existing mock role CRUD now persists additions, edits, and deletions for the lifetime of the mock server. `/routes` supplies the visual editor's catalog; `/user/routes` selects the saved role using the mock token and retains the public not-found redirect. Saving nested selections updates a parent redirect if its target was removed. Editing the signed-in user's role refreshes the router and visited-view cache immediately. A server-mode role switch returns to the dashboard so a removed page is not left mounted. Restarting the development server resets this demonstration data.
|
||||
|
||||
For a real backend, persist role/menu associations, derive permissions from the authenticated session, and independently authorize every protected API operation. Replace the existing demonstration token-query convention with your backend's authentication contract. This frontend controls navigation; it does not replace backend access checks.
|
||||
@ -35,7 +35,30 @@ const roles = [
|
||||
}
|
||||
]
|
||||
|
||||
function userRoutes(token) {
|
||||
const role = roles.find(item => token === item.key + '-token')
|
||||
if (!role) return null
|
||||
const publicPaths = constantRoutes.map(route => route.path || '/')
|
||||
// Public pages stay in the local router; only protected pages are added here.
|
||||
const protectedRoutes = role.routes.filter(route => !publicPaths.includes(route.path || '/') && route.path !== '*')
|
||||
// Keep the public not-found page reachable even after a role's menus are edited.
|
||||
const notFoundRoute = asyncRoutes.find(route => route.path === '*')
|
||||
return deepClone(notFoundRoute ? protectedRoutes.concat(notFoundRoute) : protectedRoutes)
|
||||
}
|
||||
|
||||
function notFound() {
|
||||
return { code: 50000, message: 'Role does not exist.' }
|
||||
}
|
||||
|
||||
module.exports = [
|
||||
{
|
||||
url: '/vue-element-admin/user/routes',
|
||||
type: 'get',
|
||||
response: config => {
|
||||
const data = userRoutes(config.query.token)
|
||||
return data ? { code: 20000, data } : { code: 50008, message: 'Invalid user token.' }
|
||||
}
|
||||
},
|
||||
// mock get all routes form server
|
||||
{
|
||||
url: '/vue-element-admin/routes',
|
||||
@ -64,35 +87,37 @@ module.exports = [
|
||||
{
|
||||
url: '/vue-element-admin/role',
|
||||
type: 'post',
|
||||
response: {
|
||||
code: 20000,
|
||||
data: {
|
||||
key: Mock.mock('@integer(300, 5000)')
|
||||
}
|
||||
response: config => {
|
||||
const key = String(Mock.mock('@guid'))
|
||||
const role = { ...deepClone(config.body), key }
|
||||
roles.push(role)
|
||||
return { code: 20000, data: deepClone(role) }
|
||||
}
|
||||
},
|
||||
|
||||
// update role
|
||||
{
|
||||
url: '/vue-element-admin/role/[A-Za-z0-9]',
|
||||
url: '/vue-element-admin/role/[^/]+$',
|
||||
type: 'put',
|
||||
response: {
|
||||
code: 20000,
|
||||
data: {
|
||||
status: 'success'
|
||||
}
|
||||
response: config => {
|
||||
const key = config.url.split('?')[0].split('/').pop()
|
||||
const index = roles.findIndex(role => role.key === key)
|
||||
if (index === -1) return notFound()
|
||||
roles.splice(index, 1, { ...deepClone(config.body), key })
|
||||
return { code: 20000, data: { status: 'success' } }
|
||||
}
|
||||
},
|
||||
|
||||
// delete role
|
||||
{
|
||||
url: '/vue-element-admin/role/[A-Za-z0-9]',
|
||||
url: '/vue-element-admin/role/[^/]+$',
|
||||
type: 'delete',
|
||||
response: {
|
||||
code: 20000,
|
||||
data: {
|
||||
status: 'success'
|
||||
}
|
||||
response: config => {
|
||||
const key = config.url.split('?')[0].split('/').pop()
|
||||
const index = roles.findIndex(role => role.key === key)
|
||||
if (index === -1) return notFound()
|
||||
roles.splice(index, 1)
|
||||
return { code: 20000, data: { status: 'success' } }
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@ -76,7 +76,7 @@ const asyncRoutes = [
|
||||
{
|
||||
path: '/permission',
|
||||
component: 'layout/Layout',
|
||||
redirect: '/permission/index',
|
||||
redirect: '/permission/page',
|
||||
alwaysShow: true,
|
||||
meta: {
|
||||
title: 'Permission',
|
||||
@ -246,7 +246,7 @@ const asyncRoutes = [
|
||||
},
|
||||
{
|
||||
path: 'mixchart',
|
||||
component: 'views/charts/mixChart',
|
||||
component: 'views/charts/mix-chart',
|
||||
name: 'MixChart',
|
||||
meta: { title: 'Mix Chart', noCache: true }
|
||||
}
|
||||
@ -497,19 +497,6 @@ const asyncRoutes = [
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
path: '/i18n',
|
||||
component: 'layout/Layout',
|
||||
children: [
|
||||
{
|
||||
path: 'index',
|
||||
component: 'views/i18n-demo/index',
|
||||
name: 'I18n',
|
||||
meta: { title: 'I18n', icon: 'international' }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
path: 'external-link',
|
||||
component: 'layout/Layout',
|
||||
|
||||
@ -7,6 +7,15 @@ export function getRoutes() {
|
||||
})
|
||||
}
|
||||
|
||||
export function getUserRoutes(token) {
|
||||
return request({
|
||||
url: '/vue-element-admin/user/routes',
|
||||
method: 'get',
|
||||
// Match the existing user/info mock authentication contract.
|
||||
params: { token }
|
||||
})
|
||||
}
|
||||
|
||||
export function getRoles() {
|
||||
return request({
|
||||
url: '/vue-element-admin/roles',
|
||||
|
||||
16
src/router/server-routes.js
Normal file
16
src/router/server-routes.js
Normal file
@ -0,0 +1,16 @@
|
||||
import Layout from '@/layout'
|
||||
import { mapServerRoutes } from '@/utils/server-routes'
|
||||
|
||||
// The server selects components from this build; it never supplies executable code.
|
||||
const views = require.context('../views', true, /\.vue$/, 'lazy')
|
||||
const viewKeys = views.keys()
|
||||
|
||||
export function resolveServerRoutes(routes) {
|
||||
return mapServerRoutes(routes, name => {
|
||||
if (name === 'Layout' || name === 'layout/Layout') return Layout
|
||||
if (!name.startsWith('views/')) return null
|
||||
const path = './' + name.slice('views/'.length)
|
||||
const key = [path + '.vue', path + '/index.vue'].find(item => viewKeys.includes(item))
|
||||
return key ? () => views(key).then(component => component.default || component) : null
|
||||
})
|
||||
}
|
||||
@ -1,6 +1,9 @@
|
||||
module.exports = {
|
||||
title: 'Vue Element Admin',
|
||||
|
||||
/** 'frontend' filters local routes by role; 'server' loads the user's route tree. */
|
||||
permissionMode: 'frontend',
|
||||
|
||||
/**
|
||||
* @type {boolean} true | false
|
||||
* @description Whether show the settings right-panel
|
||||
|
||||
@ -1,4 +1,7 @@
|
||||
import { asyncRoutes, constantRoutes } from '@/router'
|
||||
import { resolveServerRoutes } from '@/router/server-routes'
|
||||
import { getUserRoutes } from '@/api/role'
|
||||
import { permissionMode } from '@/settings'
|
||||
|
||||
/**
|
||||
* Use meta.role to determine if the current user has permission
|
||||
@ -47,17 +50,18 @@ const mutations = {
|
||||
}
|
||||
|
||||
const actions = {
|
||||
generateRoutes({ commit }, roles) {
|
||||
return new Promise(resolve => {
|
||||
let accessedRoutes
|
||||
if (roles.includes('admin')) {
|
||||
accessedRoutes = asyncRoutes || []
|
||||
} else {
|
||||
accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
|
||||
}
|
||||
commit('SET_ROUTES', accessedRoutes)
|
||||
resolve(accessedRoutes)
|
||||
})
|
||||
async generateRoutes({ commit, rootState }, roles) {
|
||||
let accessedRoutes
|
||||
if (permissionMode === 'server') {
|
||||
const { data } = await getUserRoutes(rootState.user.token)
|
||||
accessedRoutes = resolveServerRoutes(data)
|
||||
} else if (roles.includes('admin')) {
|
||||
accessedRoutes = asyncRoutes || []
|
||||
} else {
|
||||
accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
|
||||
}
|
||||
commit('SET_ROUTES', accessedRoutes)
|
||||
return accessedRoutes
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { login, logout, getInfo } from '@/api/user'
|
||||
import { getToken, setToken, removeToken } from '@/utils/auth'
|
||||
import router, { resetRouter } from '@/router'
|
||||
import { permissionMode } from '@/settings'
|
||||
|
||||
const state = {
|
||||
token: getToken(),
|
||||
@ -120,6 +121,10 @@ const actions = {
|
||||
|
||||
// reset visited views and cached views
|
||||
dispatch('tagsView/delAllViews', null, { root: true })
|
||||
if (permissionMode === 'server') {
|
||||
// Leave a page which may have been removed from the new server tree.
|
||||
router.replace('/')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
28
src/utils/server-routes.js
Normal file
28
src/utils/server-routes.js
Normal file
@ -0,0 +1,28 @@
|
||||
/** Map a server's JSON route tree to locally bundled components. */
|
||||
export function mapServerRoutes(routes, resolveComponent) {
|
||||
if (!Array.isArray(routes)) {
|
||||
throw new Error('Server routes must be an array')
|
||||
}
|
||||
|
||||
return routes.map(route => {
|
||||
if (!route || typeof route.path !== 'string') {
|
||||
throw new Error('Server routes must have a string path')
|
||||
}
|
||||
const result = { ...route }
|
||||
if (route.meta) result.meta = { ...route.meta }
|
||||
if (route.component !== undefined) {
|
||||
if (typeof route.component !== 'string') {
|
||||
throw new Error('Server route components must be local component names')
|
||||
}
|
||||
const component = resolveComponent(route.component)
|
||||
if (!component) {
|
||||
throw new Error(`Unknown server route component: ${route.component}`)
|
||||
}
|
||||
result.component = component
|
||||
}
|
||||
if (route.children !== undefined) {
|
||||
result.children = mapServerRoutes(route.children, resolveComponent)
|
||||
}
|
||||
return result
|
||||
})
|
||||
}
|
||||
@ -63,6 +63,7 @@
|
||||
import path from 'path'
|
||||
import { deepClone } from '@/utils'
|
||||
import { getRoutes, getRoles, addRole, deleteRole, updateRole } from '@/api/role'
|
||||
import { permissionMode } from '@/settings'
|
||||
|
||||
const defaultRole = {
|
||||
key: '',
|
||||
@ -100,7 +101,7 @@ export default {
|
||||
async getRoutes() {
|
||||
const res = await getRoutes()
|
||||
this.serviceRoutes = res.data
|
||||
this.routes = this.generateRoutes(res.data)
|
||||
this.routes = this.generateRoutes(deepClone(res.data))
|
||||
},
|
||||
async getRoles() {
|
||||
const res = await getRoles()
|
||||
@ -115,7 +116,7 @@ export default {
|
||||
// skip some route
|
||||
if (route.hidden) { continue }
|
||||
|
||||
const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)
|
||||
const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route, basePath)
|
||||
|
||||
if (route.children && onlyOneShowingChild && !route.alwaysShow) {
|
||||
route = onlyOneShowingChild
|
||||
@ -193,6 +194,14 @@ export default {
|
||||
// recursive child routes
|
||||
if (route.children) {
|
||||
route.children = this.generateTree(route.children, routePath, checkedKeys)
|
||||
if (!route.children.length) continue
|
||||
const paths = this.leafRoutePaths(route.children, routePath)
|
||||
if (route.redirect && route.redirect !== 'noRedirect' &&
|
||||
!paths.includes(path.resolve(routePath, route.redirect))) {
|
||||
// A saved parent must not redirect to a child which was unchecked.
|
||||
if (paths.length) route.redirect = paths[0]
|
||||
else delete route.redirect
|
||||
}
|
||||
}
|
||||
|
||||
if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
|
||||
@ -201,6 +210,16 @@ export default {
|
||||
}
|
||||
return res
|
||||
},
|
||||
leafRoutePaths(routes, basePath) {
|
||||
return routes.reduce((paths, route) => {
|
||||
const routePath = path.resolve(basePath, route.path)
|
||||
if (route.children && route.children.length) {
|
||||
return paths.concat(this.leafRoutePaths(route.children, routePath))
|
||||
}
|
||||
if (!/[:*]/.test(route.path)) paths.push(routePath)
|
||||
return paths
|
||||
}, [])
|
||||
},
|
||||
async confirmRole() {
|
||||
const isEdit = this.dialogType === 'edit'
|
||||
|
||||
@ -222,6 +241,10 @@ export default {
|
||||
}
|
||||
|
||||
const { description, key, name } = this.role
|
||||
if (permissionMode === 'server' && this.$store.getters.roles.includes(key)) {
|
||||
// Re-fetch the saved server tree and discard the old router matcher/cache.
|
||||
await this.$store.dispatch('user/changeRoles', key)
|
||||
}
|
||||
this.dialogVisible = false
|
||||
this.$notify({
|
||||
title: 'Success',
|
||||
@ -235,14 +258,14 @@ export default {
|
||||
})
|
||||
},
|
||||
// reference: src/view/layout/components/Sidebar/SidebarItem.vue
|
||||
onlyOneShowingChild(children = [], parent) {
|
||||
onlyOneShowingChild(children = [], parent, basePath = '/') {
|
||||
let onlyOneChild = null
|
||||
const showingChildren = children.filter(item => !item.hidden)
|
||||
|
||||
// When there is only one child route, the child route is displayed by default
|
||||
if (showingChildren.length === 1) {
|
||||
onlyOneChild = showingChildren[0]
|
||||
onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
|
||||
onlyOneChild = { ...showingChildren[0] }
|
||||
onlyOneChild.path = path.resolve(basePath, parent.path, onlyOneChild.path)
|
||||
return onlyOneChild
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user