Role-based Authorization

Implement a class Authorization with private attributes for roles and permissions. Include methods to grant and revoke permissions, ensuring that only valid roles can have certain permissions.

Example 1:

Input: Grant: "admin", "write" 
Output: "Permission granted"

Example 2:

Input: Grant: "user", "write"
Output: "Permission denied"

Maintain a dictionary for roles and their permissions. Check the role before granting permissions.

class Authorization:
    def __init__(self):
        self._roles = {'admin': set(), 'user': set()}

    def grant(self, role, permission):
        if role in self._roles and (role == 'admin' or permission == 'read'):
            return "Permission granted"
            return "Permission denied"

    def revoke(self, role, permission):
        if role in self._roles and permission in self._roles[role]:

# Test the class
authorization = Authorization()
authorization.grant('admin', 'write')  # Output: Permission granted
authorization.grant('user', 'write')  # Output: Permission denied

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!