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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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