Home  >  Article  >  Web Front-end  >  How to operate user permissions in Vue2.0

How to operate user permissions in Vue2.0

php中世界最好的语言
php中世界最好的语言Original
2018-04-14 13:54:291501browse

This time I will show you how to operate user permissions in Vue2.0, what are the precautions for operating user permissions in Vue2.0, the following is a practical case, let's take a look.

Vue-Access-Control is a front-end user permission control solution based on Vue/Vue-Router/axios. It enables developers to control routing, views, and requests at three levels: User permission control at any granularity can be achieved.

Install

Version requirements

Vue 2.0x
Vue-router 3.x
Get

git: git clone https://github.com/tower1229/Vue-Access-Control.git

npm: npm i vue-access-control

Run

//开发
npm run dev
//构建
npm build

Overview

the whole idea

At the beginning of the session, first initialize a Vue instance with only login routing, and direct the routing to the login page in the root component created hook. User loginAfter success, the front end gets the user token, and sets the axios instance to unify the request. Add {"Authorization":token} to the headers to implement user authentication, and then obtain the current user's permission data, which mainly includes routing permissions and resource permissions. Then dynamically add routes, generate menus, implement permission instructions and global permission verification methods, and provide axios with The instance adds a request interceptor, and the permission control initialization is completed. After dynamically loading the route, the routing component will be loaded and rendered, and then the front-end interface will be displayed.

In order to solve the problem of browser refresh route reset, after getting the token, it must be saved to sessionStorage. The created hook of the root component is responsible for checking whether there is a local token. If there is, there is no need to log in and directly use the token to obtain permissions and initialize it. If The token is valid and the current route has access, and the routing component will be loaded and displayed correctly; if the current route does not have access, it will jump to 404 according to the routing settings; if the token is invalid, the backend should return a 4xx status code, and the frontend will uniformly add errors to the axios instance. Interceptor, when encountering the 4xx status code, perform the exit operation, clear the sessionStorage data and jump to the login page, allowing the user to log in again.

The principle of minimal dependence

Vue-Access-Control is positioned as a single-domain solution. It has no other dependencies except Vue/Vue-Router/axios. In theory, it can be applied to any Vue project that has permission control requirements. The project is based on webpack Template development builds, most new projects can be developed directly based on the checked out code. It should be noted that the additional Element-UI and CryptoJS introduced in the project are only used to develop the demonstration interface. They are not necessary and have nothing to do with permission control. You can choose them by yourself in the project application.

Directory structure

src/
 |-- api/     //接口文件
 |  |-- index.js    //输出通用axios实例
 |  |-- account.js   //按业务模块组织的接口文件,所有接口都引用./index提供的axios实例
 |-- assets/
 |-- components/
 |-- router/
 |  |-- fullpath.js   //完整路由数据,用于匹配用户的路由权限得到实际路由
 |  `-- index.js   //输出基础路由实例
 |-- views/
 |-- App.vue
 ·-- main.js

Data format convention

Routing permission data must be an object array in the following format. Two routes with the same id and parent_id have a superior-subordinate relationship. If you want to use routing data in a custom format, you need to modify the relevant implementation of routing control.

[
 {
  "id": "1",
  "name": "菜单1",
  "parent_id": null,
  "route": "route1"
 },
 {
  "id": "2",
  "name": "菜单1-1",
  "parent_id": "1",
  "route": "route2"
 }
 ]

Resource permission data must be an object array in the following format. Each object represents a RESTful request and supports URLs with parameters.

[
 {
  "id": "2c9180895e172348015e1740805d000d",
  "name": "账号-获取",
  "url": "/accounts",
  "method": "GET"
 },
 {
  "id": "2c9180895e172348015e1740c30f000e",
  "name": "账号-删除",
  "url": "/account/**",
  "method": "DELETE"
 }
]

Routing control

Routing control includes two parts: dynamic registration of routes and dynamic generation of menus.

Dynamic registration routing

The initially instantiated route only includes two paths: login and 404. We expect the complete route to look like this:

[{
 path: '/login',
 name: 'login',
 component: (resolve) => require(['../views/login.vue'], resolve)
}, {
 path: '/404',
 name: '404',
 component: (resolve) => require(['../views/common/404.vue'], resolve)
}, {
 path: '/',
 name: '首页',
 component: (resolve) => require(['../views/index.vue'], resolve),
 children: [{
 path: '/route1',
 name: '栏目1',
 meta: {
  icon: 'icon-channel1'
 },
 component: (resolve) => require(['../views/view1.vue'], resolve)
 }, {
 path: '/route2',
 name: '栏目2',
 meta: {
  icon: 'ico-channel2'
 },
 component: (resolve) => require(['../views/view2.vue'], resolve),
 children: [{
  path: 'child2-1',
  name: '子栏目2-1',
  meta: {
  
  },
  component: (resolve) => require(['../views/route2-1.vue'], resolve)
 }]
 }]
}, {
 path: '*',
 redirect: '/404'
}]

Then you need to obtain the homepage and its sub-routes. The idea is to store the complete routing data of the entire project locally in advance, and then filter the complete routes according to user permissions.

The implementation idea of ​​filtering is to first process the routing data returned by the backend into the following hash structure:

let hashMenus = {
 "/route1":true,
 "/route1/route1-1":true,
 "/route1/route1-2":true,
 "/route2":true,
 ...
}

Then traverse the local complete route, and splice the path into the key format in the above structure in the loop. You can judge whether the route matches through hashMenus[route]. For specific implementation, see the getRoutes() method in the App.vue file.

If the routing permission data returned by the backend is different from the agreement, you need to implement the filtering logic yourself. As long as you can get the actual available routing data, you can finally use the addRoutes() method to dynamically add them to the routing instance. Pay attention to the ambiguity of the 404 page. Matching must come last.

Dynamic menu

路由数据可以直接用来生成导航菜单,但路由数据是在根组件中得到的,导航菜单存在于index.vue组件中,显然我们需要通过某种方式共享菜单数据,方法有很多,一般来说首先想到的是Vuex,但菜单数据在整个用户会话过程中不会发生改变,这并不是Vuex的最佳使用场景,而且为了尽量减少不必要的依赖,这里用了最简单直接的方法,把菜单数据挂在根组件data.menuData上,在首页里用this.$parent.menuData获取。

另外,导航菜单很可能会有添加栏目图标的需求,这可以通过在路由中添加meta数据实现,例如将图标class或unicode存到路由meta里,模板中就可以访问到meta数据,用来生成图标标签。

在多角色系统中可能遇到的一个问题是,不同角色有一个名字相同但功能不同的路由,比如说系统管理员和企业管理员都有”账号管理”这个路由,但他们的操作权限和目标不同,实际上是两个完全不同的界面,而Vue不允许多个路由同名,因此路由的name必须做区分,但把区分后的name显示在前端菜单上会很不美观,为了让不同角色可以享有同一个菜单名称,我们只要将这两个路由的meta.name都设置成”账号管理”,在模板循环时优先使用meta.name就可以了。

菜单的具体实现可以参考views/index.vue。

视图控制

视图控制的目标是根据当前用户权限决定界面元素显示与否,典型场景是对各种操作按钮的显示控制。实现视图控制的本质是实现一个权限验证方法,输入请求权限,输出是否获准。然后配合v-if或jsx或自定义指令就能灵活实现各种视图控制。

全局验证方法

验证方法的的实现本身很简单,无非是根据后端给出的资源权限做判断,重点在于优化方法的输入输出,提升易用性,经过实践总结最终使用的方案是,将权限跟请求同时维护,验证方法接收请求对象数组为参数,返回是否具有权限的布尔值。

请求对象格式:

//获取账户列表
const request = {
 p: ['get,/accounts'],
 r: params => {
 return instance.get(`/accounts`, {params})
 }
}

权限验证方法$_has()的调用格式:

v-if="$_has([request])"

权限验证方法的具体实现见App.vue中Vue.prototype.$_has方法。

将权限验证方法全局混入,就可以在项目中很容易的配合v-if实现元素显示控制,这种方式的优点在于灵活,除了可以校验权限外,还可以在判断表达式中加入运行时状态做更多样性的判断,而且可以充分利用v-if响应数据变化的特点,实现动态视图控制。

具体实现细节参考基于Vue实现后台系统权限控制中的相关章节。

自定义指令

v-if的响应特性是把双刃剑,因为判断表达式在运行过程中会频繁触发,但实际上在一个用户会话周期内其权限并不会发生变化,因此如果只需要校验权限的话,用v-if会产生大量不必要的运算,这种情况只需在视图载入时校验一次即可,可以通过自定义指令实现:

//权限指令
Vue.directive('has', {
 bind: function(el, binding) {
 if (!Vue.prototype.$_has(binding.value)) {
  el.parentNode.removeChild(el);
 }
 }
});

自定义指令内部仍然是调用全局验证方法,但优点在于只会在元素初始化时执行一次,多数情况下都应该使用自定义指令实现视图控制。

请求控制

请求控制是利用axios拦截器实现的,目的是将越权请求在前端拦截掉,原理是在请求拦截器中判断本次请求是否符合用户权限,以决定是否拦截。

普通请求的判断很容易,遍历后端返回的的资源权限格式,直接判断request.method和request.url是否吻合就可以了,对于带参数的url需要使用通配符,这里需要根据项目需求前后端协商一致,约定好通配符格式后,拦截器中要先将带参数的url处理成约定格式,再判断权限,方案中已经实现了以下两种通配符格式:

1. 格式:/resources/:id
 示例:/resources/1
 url: /resources/**
 解释:一个名词后跟一个参数,参数通常表示名词的id
 
2. 格式:/store/:id/member
 示例:/store/1/member
 url:/store/*/member
 解释:两个名词之间夹带一个参数,参数通常表示第一个名词的id

对于第一种格式需要注意的是,如果你要发起一个url为"/aaa/bbb"的请求,默认会被处理成"/aaa/**"进行权限校验,如果这里的”bbb”并不是参数而是url的一部分,那么你需要将url改成"/aaa/bbb/",在最后加一个”/“表示该url不需要转化格式。

For the specific implementation of the interceptor, see the setInterceptor() method in App.vue.

If your project requires other wildcard formats, you only need to implement the corresponding detection and conversion methods in the interceptor.

Demonstration and instructions

Demo description:

The DEMO project demonstrates dynamic menu, dynamic routing, button permissions, and request interception.

The backend of the demo project generates mock data by rap2. The login request should usually be in POST mode. However, because the programming mode of rap2 cannot obtain the non-GET request parameters , so the GET mode can only be used to log in. In the actual project Not recommended to follow;

In addition, the interface for obtaining permissions after logging in does not need to carry additional parameters. The backend can implement user authentication based on the token information carried in the request header. However, because the programming mode of rap2 cannot obtain headers data, it can only add an "Authorization" parameter. Used to generate simulation data.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

node.js implements multi-user web terminal operation

Add pop-up dialogue in WeChat applet frame

The above is the detailed content of How to operate user permissions in Vue2.0. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn