Vue. JS quick start 7: system permission management

Awakening mage 2022-06-23 15:27:11 阅读数:697

vue.vuejsquickstart

         In each system project , Are inseparable from the management of permissions . Some small projects for rapid development , Permission processing may be omitted ; But large and medium-sized projects cannot be avoided , The personnel for medium and large-scale systems are quite complicated , Everyone is in a different position or authority , The information you see is different .

         Rights management , Usually built first “ role ”, Add some column display permissions to the role , Or give permission to add, delete and modify , then “ role ” Assign to the corresponding user . A user may have only one role , Or multiple roles , So the user has these “ role ” Permission set for .

  • Such as A The role of the user is “ Super administrator ”, You have all permissions , Any page and function of the system can be viewed at will ;
  • Such as B The role of the user is the operation and maintenance personnel , You can only see some function pages of operation and maintenance , And the right to view and edit .

        Let's go through the code , To handle the permission of column display , To find out whether the front end deals with permission issues .

One 、 newly build db.js, Store analog data

         The previous articles have described how to use mockjs And define simulation data , I won't go into that , The code is as follows :

import { Random } from 'mockjs'
const DBdata = new Map();
DBdata.set(' Column list ', [
{
"name": " home page ",
"path": "/home/index",
"permission": ["view-home"],
"icon": "el-icon-data-line"
},
{
"name": " Column management ",
"path": "/category/index",
"permission": ["view-category"],
"icon": "el-icon-data-board",
},
{
"name": " User management ",
"path": "/user/index",
"permission": ["view-user"],
"icon": "el-icon-pie-chart"
},
{
"name": " Role management ",
"path": "/role/index",
"permission": ["view-role"],
"icon": "el-icon-data-analysis"
},
{
"name": " Settings management ",
"path": "/setting/index",
"permission": ["view-setting"],
"icon": "el-icon-collection-tag",
}
]);
DBdata.set(' User information ', {
username: 'test',
avatar: '',
company: '',
rolename: ' Administrators ',
roles: ['view-home', 'view-category', 'view-user', 'view-setting']
});
export default DBdata;

         Code above , If the user roles In the list , take view-setting Remove , Then the user has no permission to display system settings , This column will not display .

Two 、 Create analog interface data

         newly build mock/index.js, Used to define analog interfaces , The code is as follows :

import { mock } from 'mockjs'
import DBData from '@/db'
/**
* Get column list information
*/
mock('/api/user/info', 'get', (request, response) => {
return {
code: 200,
data: {
userinfo: DBData.get(' User information ').map(item => item),
menu: DBData.get(' Column list ').map(item => item),
token: 'kjadfakldho134koadf82389adfklkj123409jaldkfaljk2134j'
},
message: 'success'
};
});

3、 ... and 、 establish API request

        api Created in index.js, Create interface request function , Yes axios Requesting encapsulation request.js file , The front-end space has been explained , Just take the code and use it .

import Service from '@/utils/request'
export const getUserInfo = () => {
return Service.get('/api/user/info', {});
}

Four 、 Definition store State Manager

        store In the state manager , Add relevant data . Here are two main functions :

  1. adopt getters Calculate the column list with display permission
  2. add to actions Business function function , In the routing hook subfunction , Add permission filter , If it is not within the permission, it cannot be accessed directly through the route .

4.1 state Defining variables

        stay store in state.js Define the corresponding variables in , The code is as follows :

const state = {
// Column list
category: [],
// The access token
token: '',
// User information
userInfo: {},
// Character list
roles: []
}
export default state;

4.2 getters Define the corresponding calculation properties

        getters.js The document defines , The point here is categoryRoleList function , Return the displayable column data , Get the list data in the column list for display . The code is as follows :

const getters = {
userInfo(state){
let { username, company } = state.userInfo;
return { username, company };
},
roleList(state){
return state.roles;
},
categoryList(state){
return state.category;
},
// Get the list of columns that can be displayed
categoryRoleList(state){
return state.category.filter(
item => Array.isArray(item['permission'])&&
(
item.permission.length==0 || // Without permission information , Directly through
state.roles.filter(sub => item.permission.includes(sub.roleName)).length>0 // In the permission array , Can pass
)
);
}
}
export default getters;

4.3 mutationsType The type definition

        mutationsType.js The following constant values are defined in the file , The code is as follows :

export const USERINFO = "USERINFO";
export const TOKEN = "TOKEN";
export const ROLES = "ROLES";
export const CATEGORY_LIST = "CATEGORY_LIST";

4.4 mutations.js file

        mutations Define functions to modify variable values , The code is as follows :

import { USERINFO, TOKEN, ROLES, CATEGORY_LIST } from './../mutationsType'
const mutations = {
[USERINFO](state, param){
state.userInfo = param;
},
[TOKEN](state, param){
state.token = param;
}
[CATEGORY_LIST](state, param){
state.category = param;
},
[ROLES](state, param){
state.roles = param;
}
}
export default mutations;

4.5 actions Define business logic functions

        Only... Is used here vuex The state manager stores data , Data persistence is required , Can increase localstorage or sessionstorage Local storage , When a page is refreshed or revisited , Re cache local data to vuex in .

         The point here is checkRolesRoutePermission Business function , Put it in router In the hook function of , Used to prevent route jump without access permission . The code is as follows :

import { USERINFO, TOKEN, ROLES, CATEGORY_LIST } from './../mutationsType'
const actions = {
// login information
loginInfo({commit}, params){
commit(USERINFO, params.userinfo);
commit(TOKEN, params.token);
commit(ROLES, params.roles);
commit(CATEGORY_LIST, params.menu);
},
// Check whether the route has permission
checkRolesRoutePermission({ commit, getters }, param){
let DGFilter = (_child, _path) => {
return Array.isArray(_child) && _child.length>0 && _child.filter( item => item.path == _path || DGFilter(item['children'], _path) ).length > 0;
};
return new Promise((resolve, reject) => {
let { categoryList, roleList } = getters,
// Filter out the front-line columns corresponding to the current path
filterMenuList = categoryList.filter(
item => item.path == param || DGFilter(item['children'], param)
);
// If there is filtered data in the menu list , Entry processing , Otherwise release
if(filterMenuList.length>0){
let _permission = filterMenuList[0]['permission'];
// If the permission list in the menu list is longer than 0, Indicates that you have permission data , Entry processing , Otherwise release
if(Array.isArray(_permission)&&_permission.length>0){
// Judge the roles in the list , Whether the permission exists , If it exists, it can be released , non-existent , It's impassable
if( roleList.filter(item => _permission.includes(item.roleName)).length>0 ){
resolve();
}else{
reject({
code: 404,
message: " The current page has no access rights "
});
}
}else{
resolve();
}
});
},
}
export default actions;

5、 ... and 、 Add verification permission to the route

         stay router Create... In the directory index.js file , Define the system route , And filter the route through the tick function . When a page jumps through a route , If you do not have access , Directly jump to the page without access rights .getters The list of columns that you have access to has been obtained in , Access to the page without permission from the column has been blocked , For example, the address bar of the browser can be accessed directly through the route , Will be passed through the following code , Route guards intercept .

import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
//......
let _router = new Router({
routes: [
{
path: '/',
name: 'Index',
component: Index,
},
//......
{
path: '/no-permission',
name: 'Error405',
component: Error405,
},
{
path: '*',
name: 'Error404',
component: Error404,
},
]
});
_router.beforeEach((toRoute, fromRoute, next) => {
// Check whether the route has permission
store.dispatch('checkRolesRoutePermission', toRoute.path).then(res => {
if(toRoute.path!=fromRoute.path){
next();
}
}).catch(e => {
if(toRoute.path!=fromRoute.path){
next(e.code==405?'/no-permission':'/error');
}
});
});
export default _router;

6、 ... and 、 Access to user information and menu permissions

6.1 Implement login function

        When the user logs in successfully , You can get the user's role information , And column list information . Put user information , The access token , Permission data and other information are stored in Store The code in the state manager is as follows :

<script>
import { getUserInfo } from '@/api/index'
export default {
data(){
return {
}
},
methods: {
// Login Events
login(){
//do something....
this.updateUserinfo();
},
// Get user information
updateUserinfo(){
getUserInfo({
// Incoming login information
//...
}).then(res => {
if(res.code==200){
// Store user information in vuex in
this.$store.dispatch('loginInfo', {
userinfo: res.data['userinfo'],
token: res.data['token'],
menu: res.data['menu'],
roles: res.data['userinfo']['roles']
});
}
});
}
}
}
</script>

        The above login page only shows the code of the business part ,dom Some of you can use element-ui Combined quick build .

6.2 Column list displays

        Display the column list with permission filtering , The code is as follows :

<template>
<div class="category-list">
<div class="list-item"
v-for="(item, index) in categoryRoleList"
:key="index">
<h3>{
{item.name}}</h3>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
data(){
return {
}
},
computed: {
// Get the list of displayable Columns
...mapGetters(['categoryRoleList'])
},
methods: {
}
}
</script>

The above explanation is to dynamically obtain all columns and their corresponding permissions through the background , And dynamically obtain the user's role information , Perform permission display and access restriction matching each other . The above is only for your reference and study .

版权声明:本文为[Awakening mage]所创,转载请带上原文链接,感谢。 https://qdmana.com/2022/174/202206231337424603.html