'Role based system in Tree User Structure

So I am using Node/MongoDB (mongoose) to implement this feature.

What I need is the right solution for the following problem:

  1. We have many Company(ies)
  2. Each Company can create it's own Roles
  3. Role is a set of predefined Permissions (like task.create, task.read, task.update, task.delete)
  4. They can choose which Permissions are included in which Role
  5. Company can create it's own Users, and assign them a Role

Lets say that company created 3 roles (the order matters):

  1. Owner (always predefined, has all Permissions)
  2. Team Leader
  3. SuperAgent
  4. Agent

Beside that, I also have Users in a tree structure, with parent reference which holds the _id of the User above him.

The rules are:

  1. User can have none or many children
  2. User cannot be above someone that have higher role than him
  3. User cannot be below someone that have lower role than him
  4. The Tree can get as deep as they want...

So the right representation of this would be: User tree structure

But because Company Owner can at any time make new Role, or switch the order of roles, the problem occurs...

Let's say he switched the places of 2 roles, and they are now:

  1. Agent
  2. SuperAgent

How would you update all Users?

Also, what if he creates a new Role, puts it in 3rd place, and now needs to update everyone 1 role below, so he can attach that new role to a user...

What approach would you take to solve this kind of issue?



Sources

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

Source: Stack Overflow

Solution Source