roles.py 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import typing
  2. from enum import Enum
  3. from tracim_backend.exceptions import RoleDoesNotExist
  4. class WorkspaceRoles(Enum):
  5. """
  6. Available role for workspace.
  7. All roles should have a unique level and unique slug.
  8. level is role value store in database and is also use for
  9. permission check.
  10. slug is for http endpoints and other place where readability is
  11. needed.
  12. """
  13. NOT_APPLICABLE = (0, 'not-applicable')
  14. READER = (1, 'reader')
  15. CONTRIBUTOR = (2, 'contributor')
  16. CONTENT_MANAGER = (4, 'content-manager')
  17. WORKSPACE_MANAGER = (8, 'workspace-manager')
  18. def __init__(self, level, slug):
  19. self.level = level
  20. self.slug = slug
  21. @property
  22. def label(self):
  23. """ Return valid label associated to role"""
  24. # TODO - G.M - 2018-06-180 - Make this work correctly
  25. return self.slug
  26. @classmethod
  27. def get_all_valid_role(cls) -> typing.List['WorkspaceRoles']:
  28. """
  29. Return all valid role value
  30. """
  31. return [item for item in list(WorkspaceRoles) if item.level > 0]
  32. @classmethod
  33. def get_role_from_level(cls, level: int) -> 'WorkspaceRoles':
  34. """
  35. Obtain Workspace role from a level value
  36. :param level: level value as int
  37. :return: correct workspace role related
  38. """
  39. roles = [item for item in list(WorkspaceRoles) if item.level == level]
  40. if len(roles) != 1:
  41. raise RoleDoesNotExist()
  42. return roles[0]
  43. @classmethod
  44. def get_role_from_slug(cls, slug: str) -> 'WorkspaceRoles':
  45. """
  46. Obtain Workspace role from a slug value
  47. :param slug: slug value as str
  48. :return: correct workspace role related
  49. """
  50. roles = [item for item in list(WorkspaceRoles) if item.slug == slug]
  51. if len(roles) != 1:
  52. raise RoleDoesNotExist()
  53. return roles[0]