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.

88 lines
2.7 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 [role_tree for role_tree in 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 find_roles_in_hierarchy(self, request_role: Role) -> Set[Role]:
  58. """Find a set of all roles that fall within the hierarchy."""
  59. roles: List[Role] = []
  60. role_trees = self.find_role(request_role)
  61. for role_tree in role_trees:
  62. roles.extend(role_tree.get_parent_roles())
  63. return set(role for role in roles)
  64. ROLES = RoleTree(None, Role.ADMIN)
  65. ROLES.populate({
  66. Role.MODERATOR: {
  67. Role.USER: {
  68. Role.ANONYMOUS: None
  69. }
  70. },
  71. Role.AUDITOR: {
  72. Role.USER: None
  73. }
  74. })