How to set user permissions in VueJS
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 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 } } };
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: [ 'post' ], computed: { showPost() { return abilities.can('read', 'Post'); } } });
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('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) { ... };
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 '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);
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: '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
<template> <p> <p> <br /><small>posted by </small> </p> <button @click="del">Delete</button> </p> </template> <script> import axios from 'axios'; export default { props: ['post', 'username'], methods: { del() { if (this.$can('delete', this.post)) { ... } else { this.$emit('err', 'Only the owner of a post can delete it!'); } } } } </script> <style lang="scss">...</style>
点击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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Some tips for developing Android applications using Vue.js and Kotlin language. With the popularity of mobile applications and the continuous growth of user needs, the development of Android applications has attracted more and more attention from developers. When developing Android apps, choosing the right technology stack is crucial. In recent years, Vue.js and Kotlin languages have gradually become popular choices for Android application development. This article will introduce some techniques for developing Android applications using Vue.js and Kotlin language, and give corresponding code examples. 1. Set up the development environment at the beginning

Some tips for developing data visualization applications using Vue.js and Python Introduction: With the advent of the big data era, data visualization has become an important solution. In the development of data visualization applications, the combination of Vue.js and Python can provide flexibility and powerful functions. This article will share some tips for developing data visualization applications using Vue.js and Python, and attach corresponding code examples. 1. Introduction to Vue.js Vue.js is a lightweight JavaScript

The integration of Vue.js and Lua language, best practices and experience sharing for building a front-end engine for game development Introduction: With the continuous development of game development, the choice of game front-end engine has become an important decision. Among these choices, the Vue.js framework and Lua language have become the focus of many developers. As a popular front-end framework, Vue.js has a rich ecosystem and convenient development methods, while the Lua language is widely used in game development because of its lightweight and efficient performance. This article will explore how to

Integration of Vue.js and Objective-C language, tips and suggestions for developing reliable Mac applications. In recent years, with the popularity of Vue.js in front-end development and the stability of Objective-C in Mac application development, developers Start trying to combine the two to develop more reliable and efficient Mac applications. This article will introduce some tips and suggestions to help developers correctly integrate Vue.js and Objective-C and develop high-quality Mac applications. one

How to use PHP and Vue.js to implement data filtering and sorting functions on charts. In web development, charts are a very common way of displaying data. Using PHP and Vue.js, you can easily implement data filtering and sorting functions on charts, allowing users to customize the viewing of data on charts, improving data visualization and user experience. First, we need to prepare a set of data for the chart to use. Suppose we have a data table that contains three columns: name, age, and grades. The data is as follows: Name, Age, Grades Zhang San 1890 Li

How to use Vue to implement QQ-like chat bubble effects In today’s social era, the chat function has become one of the core functions of mobile applications and web applications. One of the most common elements in the chat interface is the chat bubble, which can clearly distinguish the sender's and receiver's messages, effectively improving the readability of the message. This article will introduce how to use Vue to implement QQ-like chat bubble effects and provide specific code examples. First, we need to create a Vue component to represent the chat bubble. The component consists of two main parts

Use Vue.js and Perl languages to develop efficient web crawlers and data scraping tools. In recent years, with the rapid development of the Internet and the increasing importance of data, the demand for web crawlers and data scraping tools has also increased. In this context, it is a good choice to combine Vue.js and Perl language to develop efficient web crawlers and data scraping tools. This article will introduce how to develop such a tool using Vue.js and Perl language, and attach corresponding code examples. 1. Introduction to Vue.js and Perl language

Integration of Vue.js and Dart language, practice and development skills for building cool mobile application UI interfaces Introduction: In mobile application development, the design and implementation of the user interface (UI) is a very important part. In order to achieve a cool mobile application interface, we can integrate Vue.js with the Dart language, and use the powerful data binding and componentization features of Vue.js and the rich mobile application development library of the Dart language to build Stunning mobile application UI interface. This article will show you how to
