'Define rules for the access control using CASL

I read the article from link and understand there are 3 ways to define abilities. But I have no clue to combine them together. For example, Example Tree Structure

In the three structure above, I want to restrict some users can read/write/create the group so that I choose using JSON objects to define the abilities as following:

"permissions": [
      {
        "action": "Read",
        "subject": "Group"
      },
      {
        "action": "Create",
        "subject": "Group"
      }
    ]

Each user has different permission and store in the database so that I can read it out from the database by const ability = new Ability(user.permission.rules); and then using in ability.can(Action.Read, 'Group').

However, I don't know how to add more business rules when "using JSON objects". For example, the user in Group F can only read the Group F, I and J, because I and J are under Group F. How can I achieve that?



Solution 1:[1]

CASL isn't inheritance-aware. In order to achieve what you're talking about, you'll need to generate your rules JSON from your database structure explicitly. Assuming you're doing some sort of inheritance tree in your DB structure, you would recursively query the table and then generate your rules in a flattened structure:

"permissions": [
      {
        "action": "Read",
        "subject": "GroupF"
      },
      {
        "action": "Create",
        "subject": "GroupF"
      },
      {
        "action": "View",
        "subject": "GroupF"
      },
      {
        "action": "Read",
        "subject": "GroupI"
      },
      {
        "action": "Create",
        "subject": "GroupI"
      },
      {
        "action": "View",
        "subject": "GroupI"
      },
      {
        "action": "Read",
        "subject": "GroupJ"
      },
      {
        "action": "Create",
        "subject": "GroupJ"
      },
      {
        "action": "View",
        "subject": "GroupJ"
      }
    ]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric Dieckman