A multipurpose python flask API server and administration SPA
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
4.0 KiB

  1. """Role service for Corvus."""
  2. from collections import defaultdict
  3. from enum import Enum
  4. from typing import Optional, List, Set, Dict
  5. class Role(Enum):
  6. """User role definitions."""
  7. OWNER = 'OWNER'
  8. ADMIN = 'ADMIN'
  9. AUDITOR = 'AUDITOR'
  10. MODERATOR = 'MODERATOR'
  11. USER = 'USER'
  12. ANONYMOUS = 'ANONYMOUS'
  13. NONE = 'NONE'
  14. def __str__(self):
  15. return self.value
  16. class RoleTree(defaultdict):
  17. """Simple tree structure to handle hierarchy."""
  18. def __call__(self, data: Role, power: int) -> 'RoleTree':
  19. """Handle direct calls to the tree."""
  20. return RoleTree(self, data, power)
  21. parent: Optional['RoleTree']
  22. data: Role
  23. power: int
  24. roles: Dict[Role, List['RoleTree']]
  25. def __init__(
  26. self,
  27. parent: Optional['RoleTree'],
  28. data: Role,
  29. power: int = None,
  30. **kwargs: dict) -> None:
  31. """Configure a RoleTree."""
  32. super().__init__(**kwargs)
  33. self.parent: Optional[RoleTree] = parent
  34. self.data: Role = data
  35. self.power: int = power if power is not None else 1
  36. self.default_factory = self # type: ignore
  37. self.roles: Dict[Role, List[RoleTree]] = {data: [self]}
  38. def populate(
  39. self, children: Dict[Role, Optional[dict]]) -> List['RoleTree']:
  40. """Populate a RoleTree from a dictionary of a Role hierarchy."""
  41. role_list: List[RoleTree] = [self]
  42. for child_role in children.keys():
  43. element = children[child_role]
  44. new_node = self(child_role, self.power + 1)
  45. if isinstance(element, dict) and element:
  46. role_list.extend(new_node.populate(element))
  47. else:
  48. role_list.append(new_node)
  49. self[child_role] = new_node
  50. for role_tree in role_list:
  51. if role_tree.data not in self.roles.keys():
  52. self.roles[role_tree.data] = []
  53. self.roles[role_tree.data].append(role_tree)
  54. return role_list
  55. def find_role(self, request_role: Role) -> List['RoleTree']:
  56. """Identify all instances of a role."""
  57. try:
  58. return self.roles[request_role]
  59. except KeyError:
  60. return []
  61. def get_parent_roles(self) -> List[Role]:
  62. """Return all the roles from self to the highest parent."""
  63. if self.parent is not None:
  64. return [self.data] + self.parent.get_parent_roles()
  65. return [self.data]
  66. def get_children_roles(self) -> List[Role]:
  67. """Return all the roles from self to the lowest child."""
  68. if self.roles and (
  69. len(self.roles.keys()) > 1 or len(self.roles[self.data]) > 1):
  70. child_roles = [self.data]
  71. for role in self.roles.keys():
  72. for role_tree in self.roles[role]:
  73. if role_tree.data != self.data:
  74. child_roles.extend(role_tree.get_children_roles())
  75. return child_roles
  76. return [self.data]
  77. def find_roles_in_hierarchy(self, request_role: Role) -> Set[Role]:
  78. """Find a set of all roles that fall within the hierarchy."""
  79. roles: List[Role] = []
  80. role_trees = self.find_role(request_role)
  81. for role_tree in role_trees:
  82. roles.extend(role_tree.get_parent_roles())
  83. return set(roles)
  84. def find_children_roles(self, request_role: Role) -> Set[Role]:
  85. """Find all children roles, including this role."""
  86. roles: List[Role] = []
  87. role_trees = self.find_role(request_role)
  88. for role_tree in role_trees:
  89. roles.extend(role_tree.get_children_roles())
  90. return set(roles)
  91. def __str__(self):
  92. return str(self.data)
  93. ROLES = RoleTree(None, Role.OWNER, 0)
  94. ROLE_LIST = sorted(
  95. ROLES.populate({
  96. Role.ADMIN: {
  97. Role.MODERATOR: {
  98. Role.USER: {
  99. Role.ANONYMOUS: None
  100. }
  101. },
  102. Role.AUDITOR: {
  103. Role.USER: None
  104. }
  105. }
  106. }),
  107. key=lambda rt: rt.power)