程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Djangovue implements dynamic menus and dynamic permissions

編輯:Python

Catalog

User and user group architecture design

Design and implementation of dynamic menu and authority

Vue How to implement dynamic routing at the end

Django How to implement dynamic permissions on the client

With the popularity of front-end and back-end separation architectures , stay web Application ,RESTful API It has almost become the main choice for developers , It makes the client and server do not need to save each other's details , That is, statelessness , But it is difficult to require dynamic menus and dynamic permissions in the project , This field Chat It is to provide an idea for us to solve how to implement dynamic menus and permissions in actual projects .

because RESTful API Usually stateless , How can the server know that the user has logged in ? The common practice at this time is that each request will carry a access token To authenticate users on the server . The most common is JWT 了 , If you are interested, you can learn more . Popular speaking , Used JWT The user will carry a in the request header each time Token , The server will resolve this before executing the operation Token authentication , After the authentication is completed, the server will know the user details of the request , So as to make the required return .

User and user group architecture design

Usually in a web Application design , The first is from the user 、 User group started . The user is web The core of application ,JWT Authentication also exists because of users . The user is using MySQL Of web An application is a user table , Each user is a piece of data in the user table . User groups are equivalent to the permissions of users , for example There are super administrators in the general system 、 Administrators 、 Ordinary users and other users , Users are collections under these user groups , Then user groups and users are one to many relationships , Or each user has a foreign key pointing to a user group ID. When a user is an administrator, it means that he has all the permissions under the administrator user group .

In this user group - User's architecture design , How to design permissions and menus ? First , Menus are like collections of functions operated by users , Each element in the collection is equivalent to a permission . For example, there is a menu named Employee management , There are four basic permissions under it : Look at employees 、 New employees 、 Edit employee 、 Delete employee . In other words, think of these four permissions as four methods or functions , Are these functions associated with a user group or a user ? Obviously, associating with a user group is a better choice . Because the user group can carry many menus and menu permissions , When multiple users belong to this user group , These users have all the permissions under the user group . Otherwise, it is associated with a user , Each user needs to set the menu and permission when adding , Not only a waste of time , And waste resources Occupy database space .

use RESTful API The way to do it is : Menus and permissions of user groups are stored in the permission table as records , When necessary, the server will convert these data into Json Return to the client for use , Of course, the interface that needs permission on the server will also use the data in the permission table to judge , Whether the user requesting the interface has permission to operate , Do different processing according to the authority table data .

Design and implementation of dynamic menu and authority

So how do dynamic menus and permissions accomplish these interactions on the server and client side ?

Enter the user name when logging in to the system 、 Password, etc , After successful login, the user's Token Return to the user .

Users carry this Token Request an interface of the server to obtain user details , After the server passes the authentication, it will send the user information of the user 、 The user group information and the permission information of the user group are all returned , At this point, the client user gets the permission table Json data , According to these data, the client will display different menu items .

The client receives permission Json Data time , Set according to the menu item in the permission , Dynamic setting front-end menu . Different users can display different menu items .

When a user requests another interface , The server will authenticate users first , While getting the current requesting user You will also get the user group of the user , So as to get all the permission information of the user . Then the server will do different processing according to the permission details corresponding to the interface , Finally, the corresponding information will be returned to the user . for example When it is found that the user has only view permission on the current interface , If the user initiated POST Request to add data , The server will return directly You do not have permission to perform this operation .

Vue How to implement dynamic routing at the end

Based on element For example, the management background of , stay Vue Inside use VueX State Manager , When the user logs in successfully , To get user details , After obtaining the details, according to the permission Json data , stay Store Reset the route , You should not hide or delete the needs of routing nodes . So that different users can show different menus .

Vue End implementation code example

import { login, logout, getInfo } from '@/api/login'import { getToken, setToken, removeToken } from '@/utils/auth'import router from '../../router'const user = {  state: {    token: getToken(),    name: '',    avatar: '',    roles: [],    // Automatic permission related     group_id: 0,    user_id: 0,    menu_json: [], // The permissions returned by the backend Json Stored here     router: router // Introduce the routing menu   },  mutations: {    SET_TOKEN: (state, token) => {      state.token = token    },    SET_NAME: (state, name) => {      state.name = name    },    SET_ROLES: (state, roles) => {      state.roles = roles    },    SET_MENUS: (state, menus) => {      state.menu_json = menus    },    SET_GROUP: (state, group_id) => {      state.group_id = group_id    },    SET_USER: (state, user_id) => {      state.user_id = user_id    },    SET_ROUTE: (state, router) => {      // Dynamic routing 、 Dynamic menu       console.log('router:', router.options.routes)      var group_id = localStorage.getItem('ShopGroupId')      var menus = JSON.parse(localStorage.getItem('ShopMenus'))      console.log('group_id:', localStorage.getItem('ShopGroupId'))      console.log('menus:', JSON.parse(localStorage.getItem('ShopMenus')))      console.log('group_id by 1, Do not perform setup router operation ')      if (group_id !== '1') {        for (var i in router.options.routes) {          if (router.options.routes[i].children !== undefined) {            for (var j in router.options.routes[i].children) {              if (router.options.routes[i].children[j].path !== 'dashboard') {                router.options.routes[i].children[j].hidden = true                for (var k in menus) {                  if (menus[k].object_name == router.options.routes[i].children[j].name) {                    if (menus[k].menu_list) {                      router.options.routes[i].children[j].hidden = false                    }                  }                }              }            }          }        }      }      for (var i in router.options.routes) {        if (router.options.routes[i].children !== undefined) {          var len_router = router.options.routes[i].children.length          var check_len = 0          for (var j in router.options.routes[i].children) {            if (router.options.routes[i].children[j].path !== 'dashboard') {              if (router.options.routes[i].children[j].hidden !== null && router.options.routes[i].children[j].hidden !== undefined && router.options.routes[i].children[j].hidden === true) {                check_len += 1              }            }          }          if (len_router === check_len) {            router.options.routes[i].hidden = true          }        }      }      // Dynamic routing 、 End of dynamic menu       state.router = router    }  },  actions: {    // Sign in     Login({ commit }, userInfo) {      return new Promise((resolve, reject) => {        login(userInfo).then(response => {          const data = response.data          setToken(data.token)          commit('SET_TOKEN', data.token)          resolve()        }).catch(error => {          reject(error)          alert(error)        })      })    },    // Get user information     GetInfo({ commit, state }) {      return new Promise((resolve, reject) => {        getInfo().then(response => {          const data = response.data          console.log(data)          commit('SET_NAME', data.username)          commit('SET_ROLES', [data.group.en_name])          commit('SET_MENUS', data.group.back_menu) // Save the returned permission data           commit('SET_GROUP', data.group.id)          commit('SET_USER', data.id)          localStorage.setItem('ShopMenus', JSON.stringify(data.group.back_menu))          localStorage.setItem('ShopGroupId', data.group.id)          commit('SET_ROUTE', router)          resolve(response)        }).catch(error => {          reject(error)        })      })    },    // front end Log out     FedLogOut({ commit }) {      return new Promise(resolve => {        commit('SET_TOKEN', '')        removeToken()        resolve()      })    }  }}export default userDjango How to implement dynamic permissions on the client

stay Django In the use of Permission Combined permission table , Before each interface is called, judge according to the permission , Whether the user calling the interface has permission to operate , If yes, continue to complete the following operations , Otherwise, go straight back to No right to operate The hint of .

Django The end code example is as follows

from rest_framework import permissionsfrom rest_framework.permissions import DjangoModelPermissions, IsAdminUserfrom rest_framework.permissions import BasePermission as BPermissionfrom shiyouAuth.models import GroupMenu# The final dynamic permission class class BasePermission(object):    def base_permission_check(self, basename):        # Permission white list         if basename in ['userinfo', 'permissions', 'login', 'confdict']:            return True        else:            return False    def has_permission(self, request, view):        print(' Requested path:', request.path.split('/')[1])        basename = request.path.split('/')[1]        if self.base_permission_check(basename):            return True        admin_menu = GroupMenu.objects.filter(object_name=basename).first()        if admin_menu is None and request.user.group.id != 1:            return False        if request.user.group.id == 1:            return True        if view.action == 'list' or view.action == 'retrieve':            # View permissions             return bool(request.auth and admin_menu.menu_list == True)        elif view.action == 'create':            # Create permissions             return bool(request.auth and admin_menu.menu_create == True)        elif view.action == 'update' or view.action == 'partial_update':            # Modify the permissions             return bool(request.auth and admin_menu.menu_update == True)        elif view.action == 'destroy':            # Delete permission             return bool(request.auth and admin_menu.menu_destroy == True)        else:            return False    def has_object_permission(self, request, view, obj):        basename = request.path.split('/')[1]        if self.base_permission_check(basename):            return True        admin_menu = GroupMenu.objects.filter(object_name=basename).first()        if admin_menu is None and request.user.group.id != 1:            return False        if request.user.group.id == 1:            return True        if view.action == 'list' or view.action == 'retrieve':            # View permissions             return bool(request.auth and admin_menu.menu_list == True)        elif view.action == 'create':            # Create permissions             return bool(request.auth and admin_menu.menu_create == True)        elif view.action == 'update' or view.action == 'partial_update':            # Modify the permissions             return bool(request.auth and admin_menu.menu_update == True)        elif view.action == 'destroy':            # Delete permission             return bool(request.auth and admin_menu.menu_destroy == True)        else:            return False

This is about Django Vue This is the end of the article on implementing dynamic menus and dynamic permissions , More about Django Vue For dynamic menu and dynamic permission content, please search the previous articles of SDN or continue to browse the following related articles. I hope you can support SDN more in the future !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved