Role-Based Access Control (RBAC)

Assigning permissions to roles, rather than directly to users.

The idea

In growing systems, managing permissions per-user becomes a nightmare. Instead of giving Bob "read" and "write" access manually, we create a "Role" (like Editor). We give the Editor role those permissions, and then assign Bob to the Editor role. This creates a scalable layer of indirection.

Step 1: Alice wants to Edit. We check if she has the permission directly...

How it works

# Users have Roles. Roles have Permissions.
user_roles = {
    "alice": ["editor"],
    "bob": ["viewer"]
}

role_permissions = {
    "editor": ["read_post", "write_post", "delete_post"],
    "viewer": ["read_post"]
}

def can_user_do(user, action):
    roles = user_roles.get(user, [])
    for role in roles:
        if action in role_permissions.get(role, []):
            return True
    return False

print(can_user_do("alice", "delete_post")) # True
print(can_user_do("bob", "delete_post"))   # False

Cost

Time Complexity: O(R * P) where R is the number of roles a user has, and P is the number of permissions per role (typically negligible with sets). Space Complexity: O(U*R + R*P) to store mappings.

Watch out for