KSheng
KSheng

Reputation: 157

CASL Ability subject helper with conditions

I am testing out the use of "@casl/ability" for RBAC in express. According to CASL docs, I should be able to define conditional restrictions on attributes against actions upon subjects and in the cases where classes are not used, a subject helper function can be used to wrap DTOs.

reference: https://casl.js.org/v4/en/guide/subject-type-detection

I tried the very simple example below which should have worked. But it does not. Am I understanding it incorrectly in some ways?

import { Ability, subject } from "@casl/ability";

const ability = new Ability([
  {
    action: "write",
    subject: "docs",
    conditions: {
      publisherId: 53
    }
  }
]);

const docs = {};
// Also, if the third argument is skipped for 'fields', it throws an error
console.log(
  ability.can("write", subject("docs", docs), "", { publisherId: 53 })
);

I have a sandbox here https://codesandbox.io/s/casl-test-conditions-uzc8v?file=/src/index.js:0-286

Upvotes: 2

Views: 2847

Answers (1)

Sergii Stotskyi
Sergii Stotskyi

Reputation: 5390

You incorrectly use ability.can Check the Api docs. That’s why it throws with the error message saying that you incorrectly use can.

To fix your example:

import { Ability, subject } from "@casl/ability";

const ability = new Ability([
  {
    action: "write",
    subject: "docs",
    conditions: {
      publisherId: 53
    }
  }
]);

const docs = subject('docs', {
  publisherId: 53
}); //  “docs” type instance

console.log(
  ability.can("write", docs)
);

Upvotes: 4

Related Questions