authorization.py 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # -*- coding: utf-8 -*-
  2. from typing import TYPE_CHECKING
  3. from pyramid.interfaces import IAuthorizationPolicy
  4. from zope.interface import implementer
  5. try:
  6. from json.decoder import JSONDecodeError
  7. except ImportError: # python3.4
  8. JSONDecodeError = ValueError
  9. from tracim.exceptions import InsufficientUserWorkspaceRole, \
  10. InsufficientUserProfile
  11. if TYPE_CHECKING:
  12. from tracim import TracimRequest
  13. ###
  14. # Pyramid default permission/authorization mecanism
  15. # INFO - G.M - 12-04-2018 - Setiing a Default permission on view is
  16. # needed to activate AuthentificationPolicy and
  17. # AuthorizationPolicy on pyramid request
  18. TRACIM_DEFAULT_PERM = 'tracim'
  19. @implementer(IAuthorizationPolicy)
  20. class AcceptAllAuthorizationPolicy(object):
  21. """
  22. Empty AuthorizationPolicy : Allow all request. As Pyramid need
  23. a Authorization policy when we use AuthentificationPolicy, this
  24. class permit use to disable pyramid authorization mecanism with
  25. working a AuthentificationPolicy.
  26. """
  27. def permits(self, context, principals, permision):
  28. return True
  29. def principals_allowed_by_permission(self, context, permission):
  30. raise NotImplementedError()
  31. ###
  32. # Authorization decorators for views
  33. # INFO - G.M - 12-04-2018
  34. # Instead of relying on pyramid authorization mecanism
  35. # We prefer to use decorators
  36. def require_profile(group):
  37. """
  38. Decorator for view to restrict access of tracim request if profile is
  39. not high enough
  40. :param group: value from Group Object
  41. like Group.TIM_USER or Group.TIM_MANAGER
  42. :return:
  43. """
  44. def decorator(func):
  45. def wrapper(self, context, request: 'TracimRequest'):
  46. user = request.current_user
  47. if user.profile.id >= group:
  48. return func(self, context, request)
  49. raise InsufficientUserProfile()
  50. return wrapper
  51. return decorator
  52. def require_workspace_role(minimal_required_role):
  53. """
  54. Decorator for view to restrict access of tracim request if role
  55. is not high enough
  56. :param minimal_required_role: value from UserInWorkspace Object like
  57. UserRoleInWorkspace.CONTRIBUTOR or UserRoleInWorkspace.READER
  58. :return: decorator
  59. """
  60. def decorator(func):
  61. def wrapper(self, context, request: 'TracimRequest'):
  62. user = request.current_user
  63. workspace = request.current_workspace
  64. if workspace.get_user_role(user) >= minimal_required_role:
  65. return func(self, context, request)
  66. raise InsufficientUserWorkspaceRole()
  67. return wrapper
  68. return decorator