predicates.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- coding: utf-8 -*-
  2. from tg import abort
  3. from tg import request
  4. from tg import tmpl_context
  5. from tracim.lib.utils import lazy_ugettext as l_
  6. from tg.i18n import ugettext as _
  7. from tg.predicates import Predicate
  8. from tracim.model.data import ContentType
  9. from tracim.lib.base import logger
  10. from tracim.lib.content import ContentApi
  11. from tracim.model.data import UserRoleInWorkspace
  12. FORBIDDEN_MSG = l_('You are not authorized to access this resource')
  13. class WorkspaceRelatedPredicate(Predicate):
  14. def __init__(self, **kwargs):
  15. super(WorkspaceRelatedPredicate, self).__init__(**kwargs)
  16. self.message = FORBIDDEN_MSG
  17. def minimal_role_level(self) -> int:
  18. """
  19. This method must be implemented in child classes. It defines the role of the user in the given workspace
  20. :return: required level associated to the predicate
  21. """
  22. raise NotImplementedError
  23. def evaluate(self, environ, credentials):
  24. # Comment next line if you want to activate the debug controller
  25. try:
  26. current_user = tmpl_context.current_user
  27. workspace = tmpl_context.workspace
  28. if workspace.get_user_role(current_user)>= self.minimal_role_level():
  29. return
  30. except Exception as e:
  31. logger.warning(self, 'Exception catched: {}'.format(e.__str__))
  32. self.unmet()
  33. self.unmet()
  34. class current_user_is_reader(WorkspaceRelatedPredicate):
  35. def minimal_role_level(self):
  36. return UserRoleInWorkspace.READER
  37. class current_user_is_contributor(WorkspaceRelatedPredicate):
  38. def minimal_role_level(self):
  39. return UserRoleInWorkspace.CONTRIBUTOR
  40. class current_user_is_content_manager(WorkspaceRelatedPredicate):
  41. def minimal_role_level(self):
  42. return UserRoleInWorkspace.CONTENT_MANAGER
  43. class current_user_is_workspace_manager(WorkspaceRelatedPredicate):
  44. def minimal_role_level(self):
  45. return UserRoleInWorkspace.WORKSPACE_MANAGER
  46. def require_current_user_is_owner(item_id: int):
  47. current_user = tmpl_context.current_user
  48. item = ContentApi(current_user, True, True).get_one(item_id, ContentType.Any)
  49. if item.owner_id!=current_user.user_id:
  50. abort(403, _('You\'re not allowed to access this resource'))