Analysis of Vue routing permission control

Front end development blog 2020-11-09 22:19:26
analysis vue routing permission control


This article has been authorized by the author to reprint

author : Humble front end
original text :https://juejin.im/post/689229...

Preface

I am mainly responsible for the development of the background system in the company , Among them, routing and authority checking are very important and basic . In the actual development project , For the control of login and routing permissions, refer to vue-element-admin This star project , And on this basis, based on business integration , I'll take this project as an example , Carefully analyze the whole process of routing and authority verification , It is also a summary of this knowledge point .

Overall project directory structure

Before we get to today's topic , Let's sort out the whole project first ,src In the catalog .

  • api: Interface request
  • assets: Static resources
  • components: General components
  • directive: Custom instruction
  • filters: Custom filter
  • icons: Icon
  • layout: Layout components ( The core of page Architecture )
  • router: Routing configuration ( Routing authority core module )
  • store: State management
  • styles: The style file
  • utils: Tool method
  • views: Page components
  • permission.js Rights management

Students who are interested in this project can , Study purposefully , In addition to the routing authority verification function , It also contains a lot of interesting features , I believe I can learn a lot .

Routing permission control logic

Routing process flow chart

 route 2.png

route 2.png

Routing processing source code analysis

Let's find permission.js file , The global route guard is defined here , It is also the key core code in routing permission . For the convenience of reading , Only the code related to routing is extracted

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' // get token from cookie
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/auth-redirect'] // White list configuration
router.beforeEach(async(to, from, next) => {
// start progress bar
NProgress.start()
// Yes token
if (hasToken) {
if (to.path === '/login')
// If the current path is /login, Redirect to home page
next({ path: '/' })
NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
} else {
// determine whether the user has obtained his permission roles through getInfo
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if (hasRoles) {
next()
} else {
try {
// Get user information
const { roles } = await store.dispatch('user/getInfo')
// According to the user's role , Dynamically generate routing
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
// Dynamic add route ( Combine basic routing information with dynamic routing )
router.addRoutes(accessRoutes)
// Continue to visit
next({ ...to, replace: true })
} catch (error) {
// Delete token
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
// Redirect to login page
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {
// No, token
if (whiteList.indexOf(to.path) !== -1) {
// If it's on the white list , No verification is required , Direct release
next()
} else {
// If it doesn't exist in the white list , Then redirect to the login page .
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
router.afterEach(() => {
// finish progress bar
NProgress.done()
})

be aware , In code /login?redirect=\${jto.path}, there redirect Parameters are mainly used for , The page path to jump after the user login successfully . The specific functions are in /views/login/index.vue Under the document

watch: {
$route: {
handler: function(route) {
const query = route.query
if (query) { // Route query parameters
this.redirect = query.redirect
this.otherQuery = this.getOtherQuery(query)
}
},
immediate: true
}
},
// methods Under the :
handleLogin() { // Login function
this.$refs.loginForm.validate(valid => {
if (valid) { // After the account password verification is successful
this.$store.dispatch('user/login', this.loginForm)
.then(() => {
// Jump directly to this.redirect The path of the page
this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
this.loading = false
})
} else {
// ..
}
})
},

Dynamic routing configuration

Let's first look at the definition of routing , stay /src/router/index.js Under the document

export const constantRoutes = [ // Used to define a common routing configuration , You don't need access
// Routing configuration object
]
export const asyncRoutes = [ // By routing meta information meta.roles To set access rights , It's an array in general
{
path: '/permission',
component: Layout,
redirect: '/permission/page',
alwaysShow: true, // will always show the root menu
name: 'Permission',
meta: {
title: 'Permission',
icon: 'lock',
roles: ['admin', 'editor'] // adopt roles Set route permissions
},
// ...
}
]

When adding routes dynamically , In essence, it is based on the user's role information in asyncRoutes Route filtering in the routing configuration array , Find the corresponding route , And constantRoutes Merge to generate the latest route .

Add routing logic diagram dynamically

 Dynamic routing generation .png

Dynamic routing generation .png

Dynamic routing source analysis

Code entry : permission.js

const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

permission/generateRoutes Method entry file :/strore/modules/permissions.js

import { asyncRoutes, constantRoutes } from '@/router'
const state = {
routes: [],
addRoutes: []
}
const mutations = {
SET_ROUTES: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes.concat(routes)
}
}
const actions = {
generateRoutes({ commit }, roles) {
return new Promise(resolve => {
let accessedRoutes
if (roles.includes('admin')) {
// If included admin, It means yes admin, Have access to all modules
accessedRoutes = asyncRoutes || []
} else {
// If it's not the Administrator , According to the user role roles And asynchronous routing
accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
}
// Store the final result in vuex in
commit('SET_ROUTES', accessedRoutes)
// resolve get out
resolve(accessedRoutes)
})
}
}

Filter asynchronous routes , And store the final results in vuex in , And the result resolve get out

export function hasPermission(roles, route) {
if (route.meta && route.meta.roles) { // If there is meta.roles
// as long as meta.roles There is the same value in the user role list , You have access to
return roles.some(role => route.meta.roles.includes(role))
} else {
// non-existent meta Or it doesn't exist meta.roles, It is a general module , Direct release
return true
}
}
export function filterAsyncRoutes(routes, roles) {
const res = []
routes.forEach(route => {
const tmp = { ...route }
if (hasPermission(roles, tmp)) { // Judge the access rights relative to each item in the routing array
if (tmp.children) {
// If there is children, The filter function is called recursively
tmp.children = filterAsyncRoutes(tmp.children, roles)
}
// Put the processed routing configuration into res in
res.push(tmp)
}
})
return res
}

Finally back to /permission.js In file

const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
// there accessRoutes It's the route after screening ,
// Finally through route.addRoutes take constRoutes and accessRoutes A merger , Generate the final access route
router.addRoutes(accessRoutes)

Expand - Button permissions

The basic process of routing permission control has been analyzed , Next, let's take a look at the implementation of button permission control in the project , The implementation is also relatively simple .

 Basic usage
<div v-permission="['admin','editor']"></div>
import store from '@/store'
function checkPermission(el, binding) {
const { value } = binding
// from store After getting our access interface in , Get user role information
const roles = store.getters && store.getters.roles
if (value && value instanceof Array) { // Determine whether the value passed in is an array , Normalized transfer value
if (value.length > 0) {
const permissionRoles = value
// As long as the incoming permissionRoles in , Contains roles One of the values is enough , It means you have authority
const hasPermission = roles.some(role => {
return permissionRoles.includes(role)
})
// Delete without permission , Don't show .
// v-permission The specific implementation can be modified according to the business scenario
if (!hasPermission) {
el.parentNode && el.parentNode.removeChild(el)
}
}
} else {
throw new Error(`need roles! Like v-permission="['admin','editor']"`)
}
}
export default {
inserted(el, binding) {
checkPermission(el, binding)
},
update(el, binding) {
checkPermission(el, binding)
}
}

summary

  • There is token

    • There is user role information , This indicates that the user's final accessible route has been generated , It can be released directly
    • There is no user information

      1. Call to get user information interface , Get user information , Store user information in vuex in
      2. Judge the user role

        • If you are an administrator, you have access to all modules
        • Non administrator , Asynchronous routing needs to be filtered , By traversing asynchronous routes , And pass meta.roles Compare with user information , Determine whether the user has access rights
      3. Store the final accessible route to vuex in , Finally through router.addRoutes, Integrate the final routing configuration list
  • non-existent token

    • If the access route is under the white list , We will visit directly
    • The access route does not exist under the white list , Then redirect to the login page path: /login?redirect=/xxx, After successful login, jump to /xxx Corresponding page

Related articles

  1. Handwritten simple version vue-router
  2. Vue in Axios The packaging and API Interface management
  3. 10 A practical technique to make your Vue Code is more elegant

Last , Welcome to the official account : Front end development blog , reply 1024, Get the front-end advanced information

版权声明
本文为[Front end development blog]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple