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.

108 lines
3.5 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. ADMIN = 'ADMIN'
  8. AUDITOR = 'AUDITOR'
  9. MODERATOR = 'MODERATOR'
  10. USER = 'USER'
  11. ANONYMOUS = 'ANONYMOUS'
  12. NONE = 'NONE'
  13. class RoleTree(defaultdict):
  14. """Simple tree structure to handle hierarchy."""
  15. def __call__(self, data: Role) -> 'RoleTree':
  16. """Handle direct calls to the tree."""
  17. return RoleTree(self, data)
  18. # def __hash__(self):
  19. def __init__(
  20. self,
  21. parent: Optional['RoleTree'],
  22. data: Role,
  23. **kwargs: dict) -> None:
  24. """Configure a RoleTree."""
  25. super().__init__(**kwargs)
  26. self.parent: Optional[RoleTree] = parent
  27. self.data: Role = data
  28. self.default_factory = self # type: ignore
  29. self.roles: Dict[Role, List[RoleTree]] = {data: [self]}
  30. def populate(
  31. self, children: Dict[Role, Optional[dict]]) -> List['RoleTree']:
  32. """Populate a RoleTree from a dictionary of a Role hierarchy."""
  33. role_list: List[RoleTree] = []
  34. for child_role in children.keys():
  35. element = children[child_role]
  36. new_node = self(child_role)
  37. if isinstance(element, dict) and element:
  38. role_list += new_node.populate(element)
  39. self[child_role] = new_node
  40. role_list.append(new_node)
  41. for role_tree in role_list:
  42. if role_tree.data not in self.roles.keys():
  43. self.roles[role_tree.data] = []
  44. self.roles[role_tree.data].append(role_tree)
  45. return role_list
  46. def find_role(self, request_role: Role) -> List['RoleTree']:
  47. """Identify all instances of a role."""
  48. try:
  49. return self.roles[request_role]
  50. except KeyError:
  51. return []
  52. def get_parent_roles(self) -> List[Role]:
  53. """Return all the roles from self to the highest parent."""
  54. if self.parent is not None:
  55. return [self.data] + self.parent.get_parent_roles()
  56. return [self.data]
  57. def get_children_roles(self) -> List[Role]:
  58. """Return all the roles from self to the lowest child."""
  59. if self.roles and (
  60. len(self.roles.keys()) > 1 or len(self.roles[self.data]) > 1):
  61. child_roles = [self.data]
  62. for role in self.roles.keys():
  63. for role_tree in self.roles[role]:
  64. if role_tree.data != self.data:
  65. child_roles.extend(role_tree.get_children_roles())
  66. return child_roles
  67. return [self.data]
  68. def find_roles_in_hierarchy(self, request_role: Role) -> Set[Role]:
  69. """Find a set of all roles that fall within the hierarchy."""
  70. roles: List[Role] = []
  71. role_trees = self.find_role(request_role)
  72. for role_tree in role_trees:
  73. roles.extend(role_tree.get_parent_roles())
  74. return set(roles)
  75. def find_children_roles(self, request_role: Role) -> Set[Role]:
  76. """Find all children roles, including this role."""
  77. roles: List[Role] = []
  78. role_trees = self.find_role(request_role)
  79. for role_tree in role_trees:
  80. roles.extend(role_tree.get_children_roles())
  81. return set(roles)
  82. ROLES = RoleTree(None, Role.ADMIN)
  83. ROLES.populate({
  84. Role.MODERATOR: {
  85. Role.USER: {
  86. Role.ANONYMOUS: None
  87. }
  88. },
  89. Role.AUDITOR: {
  90. Role.USER: None
  91. }
  92. })