CASL user update has been refreshed

My CASL implementation is quite basic and I've noticed that the documentation lacks detail. The code I'm using is essentially a copy-paste from the docs:

import { abilitiesPlugin } from '@casl/vue'
import defineAbilitiesFor  from './ability'

const ability = defineAbilitiesFor({name: 'guest'})
Vue.use(abilitiesPlugin, ability )

The function defineAbilitiesFor is defined in the file ./ability.js as follows:

import { AbilityBuilder } from '@casl/ability'

function defineAbilitiesFor(user) {
  return AbilityBuilder.define((can, cannot) => {
     can(['read'], 'foo', { username: user.name})
  })
}

I am aware of how to update rules or conditions with ability.update([]). However, my question is: How can I update a user's information after initializing CASL? For example, after the user logs in.

Answer №1

CASL does not directly involve the user itself. Its main concern is the permissions of the user. Therefore, following a login, it is necessary to update rules by using ability.update(myRules)

Within your Login component, make sure to call

ability.update(defineRulesFor(user))
after making a login request to the API (or once information about the currently logged in user is received).

The ability can initially be an empty instance of Ability. For example:

const ability = new Ability([])

function defineRulesFor(user) {
  const { can, rules } = AbilityBuilder.extract()

  can(['read'], 'foo', { username: user.name })

  return rules
}

// After making a login request to the API (or receiving information about the currently logged in user)

login() {
  return http.post('/login')
    .then((response) => {
       ability.update(defineRulesFor(response.user))
       // at this point, the Ability instance contains rules for the returned user
    }) 
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue encountered an invalid value for the dynamic directive argument, which was expected to be a string or null, but

Hello, I am trying to use a dynamic argument for a directive in my HTML code: <div id="app5"> <p>{{message}}</p> <button v-on:[eventName]="reverseMessage">Reverse Message</button> </div> Here is my Vue instance ...

Configuring the default value for a selection menu in Vue3

Obtaining all available categories: const fetchCategories = async () => { let response = await axios.get(`/api/get_all_category/`) categories.value = response.data.categories } The structure of categories.value is shown here: https://i.sstatic.net ...

Use Node-RED to fetch JSON or CSV data and store it in InfluxDB

Versions Node-RED v0.16.2 InfluxDB v1.2.2 Grafana v4.2.0 Ubuntu 16.04.2 I'm looking to access weather data from a local official weather station. The options available are in either csv or JSON format. I am attempting to retrieve the JSON feed us ...

Implementing type-based validations in Vue.js 3 using Yup

Greetings! I am facing a minor issue that needs to be addressed. The scenario is as follows: I need to implement validation based on the type of member. If the member type is corporate, then the tax number should be mandatory while the phone number can be ...

Is it impossible to have Dynamic React Router and components?

Currently, I'm in the process of developing a dynamic router using React. The concept involves generating Routes based on the data (object) received from the backend: Menu Object: items: [ { name: "dashboard", icon: "da ...

What is the reason for index always being not equal to 0?

<script> var index = 0; $.getJSON("./data/data.json", function(json) { $.each(json, function(data) { var html = ""; if(index == 0) { console.log(index + " fir ...

Increase the value of $index within the ng-repeat loop

Is there a way to increment the value of $index in ng-repeat by a specific amount? For example, if I want to display two values at a time, how can I ensure that the next iteration starts with the third value instead of the second value? <div ng-contr ...

Expand the boundaries of the MUI Select to encompass a different element

Is there a way to extend the border of the MUI Select dropdown menu around the IconButton next to it? I have set up sorting options (A-Z, newest-oldest) using the Select component and included a button to reverse the direction (Z-A, oldest-newest). However ...

Using AngularJS, you can pass serialized objects as query string parameters

I'm trying to pass nested objects as query parameters from my AngularJS Controller using the following code: $scope.redirect = function () { const params = $httpParamSerializer({ initval: { user: { id: 1, ...

Select box in material design does not show an error when the value is empty

<md-input-container flex-gt-xs> <label translate>rule.type.title</label> <md-select name="type" ng-required="true" ng-model="vm.model.type" ng-change="vm.onRuleTypeChange(vm.model.type)"> <md-op ...

Issue with Mat-AutoComplete arising while utilizing a formArray

After adding a form array to account for multiple rows, I had to modify my definition from: shoppingCartList Observable<any[]>; to shoppingCartList: Observable<any[]>[] = [];. However, this change resulted in an error in my filter function whic ...

The clingy navigation bar hinders smooth scrolling to the content

My website has an image where users can click on elements to scroll down to text. However, I'm facing a problem because there is a sticky menu at the top of my website. How can I ensure that the scrolling works correctly with the sticky menu included? ...

After the request.send() function is called, the request is not properly submitted and the page automatically redirects

I'm currently working on a basic ajax comment form that includes a textarea and a yes/no radio button. If the user selects 'yes', their comments are posted and then they are redirected to a new page. If the user selects 'no', th ...

Take away the dropdown selection once the form has been submitted

Every day, a user fills out a form ten times. They choose an option from the dropdown menu, fill out the form, and submit it. I am looking for a solution to either remove the selected option once it's been submitted or mark it as complete by highlight ...

While building with Next.js, a ReferenceError may occur if the sessionStorage is not defined

While using Next.js 13 App router, I encountered an issue with storing the JWT token received upon login in session storage. It all worked smoothly when accessing the token in my page.js pages across different routes as long as the page was a client compon ...

Chrome has some issues with resizing the SVG Pattern element

Utilizing inline svgs, I have a svg circle filled with a pattern that should cover 100% of the container size. However, when the parent element is resized via JavaScript, the pattern no longer reflects the 100% width and height as expected. This issue seem ...

Creating and fetching CSV files using PHP and AJAX

I have successfully created a PHP script that generates a CSV file for automatic download by the browser. The code below shows a working version with sample data for different car models. <?php $cars = array( array("Volvo",22,18), array("BMW",15,1 ...

Looking for assistance in transferring information from one webpage to another dynamic webpage

I'm in the process of building a website to feature products using NextJs. My goal is to transfer data from one page to another dynamic page. The data I am working with consists of a json array of objects stored in a data folder within the project. Wh ...

What factors outside of the program could potentially lead to the splice function not functioning as expected?

Within my code, I encountered a peculiar issue involving a splice line along with debug lines on both sides. Take a look: const obj = { x:[1,2], y:{t:"!!!"} } const lenBefore = S.groupings.length const ret = S.groupings.splice(gix, 0, obj) console.log(`${ ...

It appears that Next.js's useDebouncedCallback function is not effectively delaying the request

I am currently learning Next.js and trying to work through the tutorial. I have hit a roadblock on this particular page: https://nextjs.org/learn/dashboard-app/adding-search-and-pagination Despite conducting an extensive web search, I couldn't find a ...