Home > Web Front-end > JS Tutorial > body text

How to set user permissions in VueJS

亚连
Release: 2018-06-08 11:47:04
Original
2942 people have browsed it

This article mainly tells you the detailed process and method of managing user permissions in VueJS applications, as well as related code display. Friends in need can refer to it.

In front-end applications that require authentication, we often want to use user roles to determine which content is visible. For example, guests can read articles, but only registered users or administrators can see the edit button.

Managing permissions in the front end can be a bit cumbersome. You may have written code like this before:

if (user.type === ADMIN || user.auth && post.owner === user.id ) {
 ...
}
Copy after login

As an alternative, a simple and lightweight library - CASL - can make managing user permissions very simple. As long as you have defined permissions using CASL and set the current user, you can change the above code to this:

if (abilities.can('update', 'Post')) {
 ...
}
Copy after login

In this article, I will show how to use Vue.js and CASL to manage permissions.

CASL Crash Course

CASL allows you to define a series of rules to limit which resources are visible to users.

For example, CASL rules can indicate which CRUD (Create, Read, Update and Delete) operations users can perform on given resources and instances (posts, articles, comments, etc.).

Suppose we have a classified ads website. The most obvious rule is:

Visitors can browse all posts

Administrators can browse all posts and can update or delete

Using CASL, we use AbilityBuilder to define the rules . Call can to define a new rule. For example:

onst { AbilityBuilder } = require('casl');

export function(type) {
 AbilityBuilder.define(can => {
  switch(type) {
   case 'guest':
    can('read', 'Post');
    break;
   case 'admin':
    can('read', 'Post');
    can(['update', 'delete'], 'Post');
    break;
   // Add more roles here
  }
 }
};
Copy after login

Now, you can use the defined rules to check application permissions.

import defineAbilitiesFor from './abilities';

let currentUser = {
 id: 999,
 name: "Julie"
 type: "registered",
};

let abilities = defineAbilitiesFor(currentUser.type);

Vue.component({
 template: `<p><p>
       <p>Please log in</p>
      `,
 props: [ &#39;post&#39; ],
 computed: {
  showPost() {
   return abilities.can(&#39;read&#39;, &#39;Post&#39;);
  }
 }
});
Copy after login

Demo Course

As a demonstration, I made a server/client application for displaying classified ad posts. The rules of this application are: users can read posts or post, but can only update or delete their own posts.

I use Vue.js and CASL to easily run and extend these rules, even if new operations or instances are added later.

Now I will take you step by step to build this application. If you want to take a look, please check out this Github repo.

Define user permissions

We define user permissions in resources/ability.js. One advantage of CASL is that it is environment independent, which means that it can run in Node as well as in the browser.

We will write the permission definition into a CommonJS module to ensure Node compatibility (Webpack can enable this module to be used on the client).

resources/ability.js

const casl = require(&#39;casl&#39;);

module.exports = function defineAbilitiesFor(user) {
 return casl.AbilityBuilder.define(
  { subjectName: item => item.type },
  can => {
   can([&#39;read&#39;, &#39;create&#39;], &#39;Post&#39;);
   can([&#39;update&#39;, &#39;delete&#39;], &#39;Post&#39;, { user: user });
  }
 );
};
Copy after login

Let’s analyze this code.

As the second parameter of the define method, we define permission rules by calling can. The first parameter of this method is the CRUD operation you want to allow, and the second is the resource or instance, in this case Post.

Note that in the second can call, we passed an object as the third parameter. This object is used to test whether the user attribute matches the user object we provide. If we don't do this, then not only the creator can delete the post, but anyone can delete it at will.

resources/ability.js

...
casl.AbilityBuilder.define(
 ...
 can => {
  can([&#39;read&#39;, &#39;create&#39;], &#39;Post&#39;);
  can([&#39;update&#39;, &#39;delete&#39;], &#39;Post&#39;, { user: user });
 }
);
Copy after login

When CASL checks an instance to assign permissions, it needs to know the type of the instance. One solution is to use the object with the subjectName method as the first parameter of the define method. The subjectName method will return the type of the instance.

We achieve this by returning type in the instance. We need to ensure that this property exists when defining the Post object.

resources/ability.js

...
casl.AbilityBuilder.define(
 { subjectName: item => item.type },
 ...
);
Copy after login

Finally, we encapsulate our permission definition into a function so that we can directly pass in a user object when we need to test permissions. It will be easier to understand in the following function.

resources/ability.js

const casl = require(&#39;casl&#39;);

module.exports = function defineAbilitiesFor(user) {
 ...
};
Copy after login

Access permission rules in Vue

Now we want to check which CRUD permissions the user has in an object in the front-end application. We need to access the CASL rules in the Vue component. This is the method:

Introduce Vue and abilities plugin. This plug-in will add CASL to the Vue prototype so that we can call it within the component.

Introduce our rules into the Vue application (for example: resources/abilities.js).

Define the current user. In actual combat, we obtain user data through the server. In this example, we simply hardcode it into the project.

Keep in mind that the abilities module exports a function, which we call defineAbilitiesFor. We will pass the user object into this function. Now, whenever we can, we can examine an object to figure out what permissions the current user has.

Add the abilities plug-in so that we can test it in the component like this: this.$can(...).

src/main.js

import Vue from &#39;vue&#39;;
import abilitiesPlugin from &#39;./ability-plugin&#39;;

const defineAbilitiesFor = require(&#39;../resources/ability&#39;);
let user = { id: 1, name: &#39;George&#39; };
let ability = defineAbilitiesFor(user.id);
Vue.use(abilitiesPlugin, ability);
Copy after login

Post Example

Our application will use classified ads posts. These objects representing posts are retrieved from the database and passed to the front-end by the server. For example:

There are two attributes that are required in our Post instance:

type attribute. CASL uses the subjectName callback in abilities.js to check which instance is being tested.

user属性。这是发帖者。记住,用户只能更新和删除他们发布的帖子。在 main.js中我们通过defineAbilitiesFor(user.id)已经告诉了CASL当前用户是谁。CASL要做的就是检查用户的ID和user属性是否匹配。

let posts = [
 {
  type: &#39;Post&#39;,
  user: 1,
  content: &#39;1 used cat, good condition&#39;
 },
 {
  type: &#39;Post&#39;,
  user: 2,
  content: &#39;Second-hand bathroom wallpaper&#39;
 }
];
Copy after login

这两个post对象中,ID为1的George,拥有第一个帖子的更新删除权限,但没有第二个的。

在对象中测试用户权限

帖子通过Post组件在应用中展示。先看一下代码,下面我会讲解:

src/components/Post.vue

<template>
 <p>
  <p>

   <br /><small>posted by </small>
  </p>
  <button @click="del">Delete</button>
 </p>
</template>
<script> import axios from &#39;axios&#39;;

 export default {
  props: [&#39;post&#39;, &#39;username&#39;],
  methods: {
   del() {
    if (this.$can(&#39;delete&#39;, this.post)) {
     ...
    } else {
     this.$emit(&#39;err&#39;, &#39;Only the owner of a post can delete it!&#39;);
    }
   }
  }
 } </script>
<style lang="scss">...</style>
Copy after login

点击Delete按钮,捕获到点击事件,会调用del处理函数。

我们通过this.$can('delete', post)来使用CASL检查当前用户是否具有操作权限。如果有权限,就进一步操作,如果没有,就给出错误提示“只有发布者可以删除!”

服务器端测试

在真实项目里,用户在前端删除后,我们会通过 Ajax发送删除指令到接口,比如:

src/components/Post.vue

if (this.$can(&#39;delete&#39;, post)) {
 axios.get(`/delete/${post.id}`, ).then(res => {
  ...
 });
}
Copy after login

服务器不应信任客户端的CRUD操作,那我们把CASL测试逻辑放到服务器:

server.js

app.get("/delete/:id", (req, res) => {
 let postId = parseInt(req.params.id);
 let post = posts.find(post => post.id === postId);
 if (ability.can(&#39;delete&#39;, post)) {
  posts = posts.filter(cur => cur !== post);
  res.json({ success: true });
 } else {
  res.json({ success: false });
 }
});
Copy after login

CASL是同构(isomorphic)的,服务器上的ability对象就可以从abilities.js中引入,这样我们就不必复制任何代码了!

封装

此时,在简单的Vue应用里,我们就有非常好的方式管理用户权限了。

我认为this.$can('delete', post) 比下面这样优雅得多:

if (user.id === post.user && post.type === &#39;Post&#39;) {
 ...
}
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

JS中的单例模式实现对数据增删改查

使用Vue仿制今日头条(详细教程)

React开发如何配置eslint

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!