Utilizing @casl/vue in conjunction with pinia: A guide to integrating these

I'm currently facing an issue with integrating @casl/ability and Vue 3 with Pinia. I'm unsure of how to make it work seamlessly.

Here is a snippet from my app.js:

import { createApp } from "vue"
const app = createApp({})

// pinetree
import pinetree from "./store"
app.use(pinetree)

// casl
import { abilitiesPlugin } from "@casl/vue"
import ability from "./cacl/ability"
app.use(abilitiesPlugin, ability, {
    useGlobalProperties: true
})

// ...

app.mount('#app')

This is what my ability.js file looks like:

import { defineAbility } from "@casl/ability"
import { useMainStore } from "../store/main"

const customAbility = defineAbility((can, cannot) => {
    const store = useMainStore()
    if (store.user.role === "admin") {
        can("read", "Post")
    }
    // ...
})

export default customAbility

An error message keeps popping up while trying to set this up:

I've referred to Pinia's documentation on Using a store outside of a component, but there seems to be something amiss in my implementation. (P.S. The Pinia setup works fine elsewhere in my project; just need guidance on getting it right here.)

Answer №1

Perhaps it would be helpful to establish rules in pinia. In order to utilize the ability there, you must first make it accessible within the store (similar to vue-router):

Main.js:

import { abilitiesPlugin } from "@casl/vue";
import { createMongoAbility } from "@casl/ability";

const ability = createMongoAbility();
app.use(abilitiesPlugin, ability);
pinia.use(({ store }) => {
  store.ability = markRaw(ability);
});

In store.js, you can now access the ability like this:

actions: {
  initCasl() {
    const builder = new AbilityBuilder(this.ability);
    if (this.user.role === "admin") {
      builder.can("read", "Post")
    }
    this.ability.update(builder.rules);
  }
}

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

Finding the location of PIE.htc in the Firebug tool

After encountering issues with CSS3 properties not working on IE 7 and IE 8, I decided to include PIE.HTC. Visit this link for more information Upon viewing the page in IE, I realized that the CSS3 properties were not being applied as expected. I attempt ...

Conceal a different CSS class if a certain CSS class is present on the page

I am currently working on organizing my page to distinguish between purchased and unsold products. For the items that have been bought, I am using the CSS class "winning_bid" within a div element. My goal is to hide another div with the class "price" if th ...

Storing a dynamically created grid of inputs using a consistent ng-model

I have the following code snippets: $scope.createPack = function(informationsPack, informationsActivite) { PackService.add(informationsPack, informationsActivite) .then(function(res) { $state.go(&apos ...

The request does not include the cookies

My ReactJS client sends a cookie using this NodeJS code snippet: res.cookie("token", jwtCreation, { maxAge: 24 * 60 * 60 * 1000, // Milliseconds (24 hours) sameSite: 'None', // Cross-site requests allowed for modern browser ...

The one-click button is functional on larger screens, while on mobile devices, only a double click will register

I am facing an issue in angular where a button works perfectly fine with one click on larger screens, such as Macbook. However, on iPhone, it requires a double click to function properly (it works fine on Android too). The alert triggers with a single cl ...

Perform an Ajax request to a C# Controller Function

In my javascript file named "data handling.js" within a folder labeled "JS", you'll find the following piece of code: document.getElementById('submit-new-project').addEventListener("click", function () { var ProjectName = document.getEl ...

Limiting the usage of a command in Discord.js to one user at a time, rather than all users

I'm in the process of developing a discord.js bot and I need to implement a cooldown for a specific command. After searching several tutorials online, I found that most of them apply the cooldown to all commands (meaning all users have to wait a set ...

Create a self-bot that can generate a new server

I am currently working on a discord.js self-bot and I need assistance in creating a server. Any guidance would be greatly appreciated. I have experimented with the client.user method, but did not achieve the desired result. If it is not possible to c ...

What options are available to enable the user to input information into the v-time-picker component?

I am looking for a solution where users can input digits into the vuetify v-time-picker, while still being able to select the time on the clock. <v-col align-self="center"> <v-menu ref="menuTimeStart" v-model="me ...

Is it more beneficial to categorize REST-based modules/controllers by resource or by specific action/feature?

I'm facing a scenario that goes like this: Endpoint 1: Retrieve all books in the United States owned by John with a GET Request to /country/us/person/john/books Endpoint 2: Get all books owned by John in every country with a GET Request to /person/j ...

I'm a beginner in React Native and I'm attempting to display a "Hello World" text when the button is pressed. Unfortunately, the code below is not

''' import { StyleSheet, Text, View, SafeAreaView, TouchableOpacity, Button } from 'react-native' import React from 'react' const handlePress = () => { <View> <Text> Greetings universe ...

Node.js: The choice between returning the original Promise or creating a new Promise instance

Currently, I am in the process of refactoring a codebase that heavily relies on Promises. One approach I am considering is replacing the new Promise declaration with simply returning the initial Promise instead. However, I want to ensure that I am correctl ...

The outcome of the Ajax response is not in accordance with my expectations

Whenever the response from my PHP echo statement in an AJAX request is "loggedIn", I want to invoke the displayUsers function. However, it seems to always skip executing displayUsers() and goes straight to the else statement. Oddly enough, when I alert the ...

Leveraging Ajax for transmitting JSON data and performing decoding operations

Previously, I used an AJAX script to fetch data from viewCommentsJson.php. The data retrieved looked like this: [{"comments":"Greta"},{"comments":"John"}]. Is there a way to decode and display this return value properly? Appreciate any assistance. Gret ...

Encountered an error while trying to access an undefined property during an Angular Karma

I'm currently working on testing a service function that involves multiple $http.get() calls. The function being tested returns a promise but the test is failing with an error stating response is undefined. Below is the test script: it('should ...

Top method for displaying loading popup using $http

As a newcomer to Angular, I am curious to know if it's possible to achieve the following scenario and also where I can find documentation to help me get started. The scenario: In my MEAN app, there is currently a 'loading...' popup controll ...

Troubleshooting: Issue with Updating Views in Angular JS

I've been attempting to change the view from the controller, but it's just not working properly. app.js var app = angular.module('vla', ['ngRoute']); app.config(function ($routeProvider){ $routeProvider ...

Exporting JSON data as an Excel file in AngularJS, including the option to customize the fonts used for the

Currently, I am working on a project where I need to convert JSON data to an Excel file using JavaScript in combination with AngularJS. So far, I have successfully converted the JSON data to CSV format. However, I faced issues with maintaining the font s ...

Using jQuery to submit data via POST method without having the page reload

I have a link in the footer that, when clicked, jumps to the header with a # in the address bar. Is there a way to prevent this and stay in the footer? Here is the code snippet: <a href="#" class="clickIn" id="1" attrIn="Like"><span style="color ...

The changes made to $scope in AngularJS are not being displayed in the view

The View Section <div class="col-sm-8" data-ng-init="init_enable_disable()"> <select class="form-control" style="margin-top: 5px;" data-ng-model="schedule.scheduleType" data-ng-change="enable_disableDiv(schedule.scheduleType);"> ...