request.py 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. # -*- coding: utf-8 -*-
  2. from pyramid.request import Request
  3. from sqlalchemy.orm.exc import NoResultFound
  4. from tracim.exceptions import NotAuthenticated
  5. from tracim.exceptions import UserNotFoundInTracimRequest
  6. from tracim.exceptions import UserDoesNotExist
  7. from tracim.exceptions import WorkspaceNotFound
  8. from tracim.exceptions import ImmutableAttribute
  9. from tracim.lib.core.user import UserApi
  10. from tracim.lib.core.workspace import WorkspaceApi
  11. from tracim.lib.utils.authorization import JSONDecodeError
  12. from tracim.models import User
  13. from tracim.models.data import Workspace
  14. class TracimRequest(Request):
  15. """
  16. Request with tracim specific params/methods
  17. """
  18. def __init__(
  19. self,
  20. environ,
  21. charset=None,
  22. unicode_errors=None,
  23. decode_param_names=None,
  24. **kw
  25. ):
  26. super().__init__(
  27. environ,
  28. charset,
  29. unicode_errors,
  30. decode_param_names,
  31. **kw
  32. )
  33. # Current workspace, found by request headers or content
  34. self._current_workspace = None # type: Workspace
  35. # Authenticated user
  36. self._current_user = None # type: User
  37. # User found from request headers, content, distinct from authenticated
  38. # user
  39. self._user_candidate = None # type: User
  40. # INFO - G.M - 18-05-2018 - Close db at the end of the request
  41. self.add_finished_callback(self._cleanup)
  42. @property
  43. def current_workspace(self) -> Workspace:
  44. """
  45. Get current workspace of the request according to authentification and
  46. request headers (to retrieve workspace). Setted by default value the
  47. first time if not configured.
  48. :return: Workspace of the request
  49. """
  50. if self._current_workspace is None:
  51. self.current_workspace = get_workspace(self.current_user, self)
  52. return self._current_workspace
  53. @current_workspace.setter
  54. def current_workspace(self, workspace: Workspace) -> None:
  55. """
  56. Setting current_workspace
  57. :param workspace:
  58. :return:
  59. """
  60. if self._current_workspace is not None:
  61. raise ImmutableAttribute(
  62. "Can't modify already setted current_workspace"
  63. )
  64. self._current_workspace = workspace
  65. @property
  66. def current_user(self) -> User:
  67. """
  68. Get user from authentication mecanism.
  69. """
  70. if self._current_user is None:
  71. self.current_user = get_auth_safe_user(self)
  72. return self._current_user
  73. @current_user.setter
  74. def current_user(self, user: User) -> None:
  75. if self._current_user is not None:
  76. raise ImmutableAttribute(
  77. "Can't modify already setted current_user"
  78. )
  79. self._current_user = user
  80. # TODO - G.M - 24-05-2018 - Find a better naming for this ?
  81. @property
  82. def candidate_user(self) -> User:
  83. """
  84. Get user from headers/body request. This user is not
  85. the one found by authentication mecanism. This user
  86. can help user to know about who one page is about in
  87. a similar way as current_workspace.
  88. """
  89. if self._user_candidate is None:
  90. self.candidate_user = get_candidate_user(self)
  91. return self._user_candidate
  92. def _cleanup(self, request: 'TracimRequest') -> None:
  93. """
  94. Close dbsession at the end of the request in order to avoid exception
  95. about not properly closed session or "object created in another thread"
  96. issue
  97. see https://github.com/tracim/tracim_backend/issues/62
  98. :param request: same as self, request
  99. :return: nothing.
  100. """
  101. self._current_user = None
  102. self._current_workspace = None
  103. self.dbsession.close()
  104. @candidate_user.setter
  105. def candidate_user(self, user: User) -> None:
  106. if self._user_candidate is not None:
  107. raise ImmutableAttribute(
  108. "Can't modify already setted candidate_user"
  109. )
  110. self._user_candidate = user
  111. ###
  112. # Utils for TracimRequest
  113. ###
  114. def get_candidate_user(
  115. request: TracimRequest
  116. ) -> User:
  117. """
  118. Get candidate user
  119. :param request: pyramid request
  120. :return: user found from header/body
  121. """
  122. app_config = request.registry.settings['CFG']
  123. uapi = UserApi(None, session=request.dbsession, config=app_config)
  124. try:
  125. login = None
  126. if 'user_id' in request.matchdict:
  127. login = request.matchdict['user_id']
  128. if not login:
  129. raise UserNotFoundInTracimRequest('You request a candidate user but the context not permit to found one') # nopep8
  130. user = uapi.get_one(login)
  131. except UserNotFoundInTracimRequest as exc:
  132. raise UserDoesNotExist('User {} not found'.format(login)) from exc
  133. return user
  134. def get_auth_safe_user(
  135. request: TracimRequest,
  136. ) -> User:
  137. """
  138. Get current pyramid authenticated user from request
  139. :param request: pyramid request
  140. :return: current authenticated user
  141. """
  142. app_config = request.registry.settings['CFG']
  143. uapi = UserApi(None, session=request.dbsession, config=app_config)
  144. try:
  145. login = request.authenticated_userid
  146. if not login:
  147. raise UserNotFoundInTracimRequest('You request a current user but the context not permit to found one') # nopep8
  148. user = uapi.get_one_by_email(login)
  149. except (UserDoesNotExist, UserNotFoundInTracimRequest) as exc:
  150. raise NotAuthenticated('User {} not found'.format(login)) from exc
  151. return user
  152. def get_workspace(
  153. user: User,
  154. request: TracimRequest
  155. ) -> Workspace:
  156. """
  157. Get current workspace from request
  158. :param user: User who want to check the workspace
  159. :param request: pyramid request
  160. :return: current workspace
  161. """
  162. workspace_id = ''
  163. try:
  164. if 'workspace_id' in request.matchdict:
  165. workspace_id = request.matchdict['workspace_id']
  166. if not workspace_id:
  167. raise WorkspaceNotFound('No workspace_id property found in request')
  168. wapi = WorkspaceApi(
  169. current_user=user,
  170. session=request.dbsession,
  171. config=request.registry.settings['CFG']
  172. )
  173. workspace = wapi.get_one(workspace_id)
  174. except JSONDecodeError:
  175. raise WorkspaceNotFound('Bad json body')
  176. except NoResultFound:
  177. raise WorkspaceNotFound(
  178. 'Workspace {} does not exist '
  179. 'or is not visible for this user'.format(workspace_id)
  180. )
  181. return workspace