search
HomeWeb Front-endJS TutorialHow to set user permissions in VueJS
How to set user permissions in VueJSJun 08, 2018 am 11:47 AM
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: [ &#39;post&#39; ],
 computed: {
  showPost() {
   return abilities.can(&#39;read&#39;, &#39;Post&#39;);
  }
 }
});

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 });
  }
 );
};

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 });
 }
);

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(&#39;casl&#39;);

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 &#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);

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;
 }
];

这两个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>

点击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 => {
  ...
 });
}

服务器不应信任客户端的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 });
 }
});

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

封装

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

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

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

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

相关文章:

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!

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
VUE3快速入门:使用Vue.js指令实现选项卡切换VUE3快速入门:使用Vue.js指令实现选项卡切换Jun 15, 2023 pm 11:45 PM

本文旨在帮助初学者快速入手Vue.js3,实现简单的选项卡切换效果。Vue.js是一个流行的JavaScript框架,可用于构建可重用的组件、轻松管理应用程序的状态和处理用户界面的交互操作。Vue.js3是该框架的最新版本,相较于之前的版本变动较大,但基本原理并未改变。在本文中,我们将使用Vue.js指令实现选项卡切换效果,目的是让读者熟悉Vue.js的

Flask + Vue.js:快速实现单页面应用Flask + Vue.js:快速实现单页面应用Jun 17, 2023 am 09:06 AM

随着移动互联网和Web技术的迅速发展,越来越多的应用需要提供流畅、快速的用户体验。传统的多页面应用已经无法满足这些需求,而单页面应用(SPA)则成为了解决方案之一。那么,如何快速实现单页面应用呢?本文将介绍如何利用Flask和Vue.js来构建SPA。Flask是一个使用Python语言编写的轻量级Web应用框架,它的优点是灵活、易扩

VUE3基础教程:使用Vue.js插件封装图片上传组件VUE3基础教程:使用Vue.js插件封装图片上传组件Jun 15, 2023 pm 11:07 PM

VUE3基础教程:使用Vue.js插件封装图片上传组件Vue.js是一款流行的前端框架,它使开发者可以用更少的代码创建更高效、灵活的应用程序。尤其是在Vue.js3发布之后,它的优化和改进使得更多的开发者倾向于使用它。这篇文章将介绍如何使用Vue.js3来封装一个图片上传组件插件。在开始之前,需要先确保已经安装了Vue.js和VueCLI。如果尚未安装

VUE3基础教程:使用Vue.js插件封装日历组件VUE3基础教程:使用Vue.js插件封装日历组件Jun 15, 2023 pm 09:09 PM

Vue.js是现代化的前端JavaScript框架之一,它提供了一套完整的工具来构建交互式用户界面。在Vue.js的生态系统中,有各种各样的插件和组件,可以大大简化我们的开发流程。在本篇文章中,我们将介绍如何使用Vue.js插件封装一个日历组件,以方便我们在Vue.js项目中快速使用。Vue.js插件Vue.js插件可以扩展Vue.js的功能。它们可以添加全

Vue.js实现登录验证的完整指南(API、JWT、axios)Vue.js实现登录验证的完整指南(API、JWT、axios)Jun 09, 2023 pm 04:04 PM

Vue.js是一种流行的JavaScript框架,用于构建动态Web应用程序。实现用户登录验证是开发Web应用程序的必要部分之一。本文将介绍使用Vue.js、API、JWT和axios实现登录验证的完整指南。创建Vue.js应用程序首先,我们需要创建一个新的Vue.js应用程序。我们可以使用VueCLI或手动创建一个Vue.js应用程序。安装axiosax

VUE3开发入门教程:使用Vue.js组件封装chart图表VUE3开发入门教程:使用Vue.js组件封装chart图表Jun 15, 2023 pm 10:29 PM

随着大数据时代的到来,数据可视化已经成为了现如今的趋势之一。在Web前端开发的过程中,如何使用Vue.js进行数据可视化处理,成为了许多前端开发者所关注的问题。本文将会介绍如何使用Vue.js组件,封装基于chart.js库的图表。1.了解chart.jsChart.js是一款基于HTML5CanvasElement的简单易用、跨平台的开源图表库,我们可

VUE3基础教程:使用Vue.js自定义事件VUE3基础教程:使用Vue.js自定义事件Jun 15, 2023 pm 09:43 PM

Vue.js是一款流行的JavaScript框架,它提供了很多方便的特性,所以它在开发Web应用程序时非常有用。Vue.js中的自定义事件系统使其更加灵活,并且可以通过组件事件触发和处理来实现更好的代码重用性。在本文中,我们将讨论如何使用Vue.js的自定义事件。Vue.js中自定义事件的基础在Vue.js中,我们可以通过v-on指令来监听DOM事件。例如,

使用Python与Vue.js开发实时同步的Web应用程序使用Python与Vue.js开发实时同步的Web应用程序Jun 17, 2023 am 08:28 AM

随着Web应用程序的普及和用户体验的要求不断提高,实时同步已经成为了现代Web应用程序不可或缺的功能。在本文中,我们将介绍如何使用Python和Vue.js开发实时同步的Web应用程序。为了实现实时同步的功能,我们需要使用一些现代化的Web技术,其中包括WebSocket、异步编程和前端框架。以下是本文中将用到的技术栈:Python3.6+FlaskFla

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools