@casl/vue: What should by ability.js file look like?

2k Views Asked by At

I'm trying to integrate @casl/vue with Vue 3, and I'm afraid I'm having problems.

Per the instructions, I've added the following to my /main.js:

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

app.use(abilitiesPlugin, ability, {
  useGlobalProperties: true
})

So far, so good. However, it's unclear what I should put in /services/ability.js.

I tried the following (based on this), and it works:

import { defineAbility } from '@casl/ability';

export default defineAbility((can, cannot) => {
  can('manage', 'all');
  cannot('delete', 'User');
});

But, of course, this doesn't allow me to use different permissions for different users.

So I tried the following instead (based on this):

import { defineAbility } from '@casl/ability';

export default (user) => defineAbility((can) => {
  can('read', 'Article');

  if (user.isLoggedIn) {
    can('update', 'Article', { authorId: user.id });
    can('create', 'Comment');
    can('update', 'Comment', { authorId: user.id });
  }
});

...and that doesn't work. In the console, I see:

plugin.ts:12 Uncaught Error: Please provide an Ability instance to abilitiesPlugin plugin
    at l (plugin.ts:12:11)
    at Object.use (runtime-core.esm-bundler.js:3812:21)
    at main.js?t=1651580949947:29:5

Got any hints? I'm finding the documentation to be pretty unclear. A practical example would really help me!

Thanks!

1

There are 1 best solutions below

0
hungify On

It means you must pass plugins as an instance of Ability

const ability = new Ability()

.use(abilitiesPlugin, ability, {
  ....
  })