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 ) { ... }
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')) { ... }
In this article, I will show how to use Vue.js and CASL to manage permissions.
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 } } };
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: `
Please log in
`, props: [ 'post' ], computed: { showPost() { return abilities.can('read', 'Post'); } } });
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.
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('casl'); module.exports = function defineAbilitiesFor(user) { return casl.AbilityBuilder.define( { subjectName: item => item.type }, can => { can(['read', 'create'], 'Post'); can(['update', 'delete'], 'Post', { user: user }); } ); };
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(['read', 'create'], 'Post'); can(['update', 'delete'], 'Post', { user: user }); } );
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 }, ... );
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('casl'); module.exports = function defineAbilitiesFor(user) { ... };
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 'vue'; import abilitiesPlugin from './ability-plugin'; const defineAbilitiesFor = require('../resources/ability'); let user = { id: 1, name: 'George' }; let ability = defineAbilitiesFor(user.id); Vue.use(abilitiesPlugin, ability);
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: 'Post', user: 1, content: '1 used cat, good condition' }, { type: 'Post', user: 2, content: 'Second-hand bathroom wallpaper' } ];
这两个post对象中,ID为1的George,拥有第一个帖子的更新删除权限,但没有第二个的。
帖子通过Post组件在应用中展示。先看一下代码,下面我会讲解:
src/components/Post.vue
posted by
点击Delete按钮,捕获到点击事件,会调用del处理函数。
我们通过this.$can('delete', post)来使用CASL检查当前用户是否具有操作权限。如果有权限,就进一步操作,如果没有,就给出错误提示“只有发布者可以删除!”
在真实项目里,用户在前端删除后,我们会通过 Ajax发送删除指令到接口,比如:
src/components/Post.vue
if (this.$can('delete', post)) { axios.get(`/delete/${post.id}`, ).then(res => { ... }); }
服务器不应信任客户端的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('delete', post)) { posts = posts.filter(cur => cur !== post); res.json({ success: true }); } else { res.json({ success: false }); } });
CASL是同构(isomorphic)的,服务器上的ability对象就可以从abilities.js中引入,这样我们就不必复制任何代码了!
此时,在简单的Vue应用里,我们就有非常好的方式管理用户权限了。
我认为this.$can('delete', post) 比下面这样优雅得多:
if (user.id === post.user && post.type === 'Post') { ... }
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
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!