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.
 
 
 
 
 
 

165 lines
6.3 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 matrix.org
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """This module contains classes for authenticating the user."""
  16. from twisted.internet import defer
  17. from synapse.api.constants import Membership
  18. from synapse.api.errors import AuthError, StoreError
  19. from synapse.api.events.room import (RoomTopicEvent, RoomMemberEvent,
  20. MessageEvent, FeedbackEvent)
  21. import logging
  22. logger = logging.getLogger(__name__)
  23. class Auth(object):
  24. def __init__(self, hs):
  25. self.hs = hs
  26. self.store = hs.get_datastore()
  27. @defer.inlineCallbacks
  28. def check(self, event, raises=False):
  29. """ Checks if this event is correctly authed.
  30. Returns:
  31. True if the auth checks pass.
  32. Raises:
  33. AuthError if there was a problem authorising this event. This will
  34. be raised only if raises=True.
  35. """
  36. try:
  37. if event.type in [RoomTopicEvent.TYPE, MessageEvent.TYPE,
  38. FeedbackEvent.TYPE]:
  39. yield self.check_joined_room(event.room_id, event.user_id)
  40. defer.returnValue(True)
  41. elif event.type == RoomMemberEvent.TYPE:
  42. allowed = yield self.is_membership_change_allowed(event)
  43. defer.returnValue(allowed)
  44. else:
  45. raise AuthError(500, "Unknown event type %s" % event.type)
  46. except AuthError as e:
  47. logger.info("Event auth check failed on event %s with msg: %s",
  48. event, e.msg)
  49. if raises:
  50. raise e
  51. defer.returnValue(False)
  52. @defer.inlineCallbacks
  53. def check_joined_room(self, room_id, user_id):
  54. try:
  55. member = yield self.store.get_room_member(
  56. room_id=room_id,
  57. user_id=user_id
  58. )
  59. if not member or member.membership != Membership.JOIN:
  60. raise AuthError(403, "User %s not in room %s" %
  61. (user_id, room_id))
  62. defer.returnValue(member)
  63. except AttributeError:
  64. pass
  65. defer.returnValue(None)
  66. @defer.inlineCallbacks
  67. def is_membership_change_allowed(self, event):
  68. # does this room even exist
  69. room = yield self.store.get_room(event.room_id)
  70. if not room:
  71. raise AuthError(403, "Room does not exist")
  72. # get info about the caller
  73. try:
  74. caller = yield self.store.get_room_member(
  75. user_id=event.user_id,
  76. room_id=event.room_id)
  77. except:
  78. caller = None
  79. caller_in_room = caller and caller.membership == "join"
  80. # get info about the target
  81. try:
  82. target = yield self.store.get_room_member(
  83. user_id=event.target_user_id,
  84. room_id=event.room_id)
  85. except:
  86. target = None
  87. target_in_room = target and target.membership == "join"
  88. membership = event.content["membership"]
  89. if Membership.INVITE == membership:
  90. # Invites are valid iff caller is in the room and target isn't.
  91. if not caller_in_room: # caller isn't joined
  92. raise AuthError(403, "You are not in room %s." % event.room_id)
  93. elif target_in_room: # the target is already in the room.
  94. raise AuthError(403, "%s is already in the room." %
  95. event.target_user_id)
  96. elif Membership.JOIN == membership:
  97. # Joins are valid iff caller == target and they were:
  98. # invited: They are accepting the invitation
  99. # joined: It's a NOOP
  100. if event.user_id != event.target_user_id:
  101. raise AuthError(403, "Cannot force another user to join.")
  102. elif room.is_public:
  103. pass # anyone can join public rooms.
  104. elif (not caller or caller.membership not in
  105. [Membership.INVITE, Membership.JOIN]):
  106. raise AuthError(403, "You are not invited to this room.")
  107. elif Membership.LEAVE == membership:
  108. if not caller_in_room: # trying to leave a room you aren't joined
  109. raise AuthError(403, "You are not in room %s." % event.room_id)
  110. elif event.target_user_id != event.user_id:
  111. # trying to force another user to leave
  112. raise AuthError(403, "Cannot force %s to leave." %
  113. event.target_user_id)
  114. else:
  115. raise AuthError(500, "Unknown membership %s" % membership)
  116. defer.returnValue(True)
  117. def get_user_by_req(self, request):
  118. """ Get a registered user's ID.
  119. Args:
  120. request - An HTTP request with an access_token query parameter.
  121. Returns:
  122. UserID : User ID object of the user making the request
  123. Raises:
  124. AuthError if no user by that token exists or the token is invalid.
  125. """
  126. # Can optionally look elsewhere in the request (e.g. headers)
  127. try:
  128. return self.get_user_by_token(request.args["access_token"][0])
  129. except KeyError:
  130. raise AuthError(403, "Missing access token.")
  131. @defer.inlineCallbacks
  132. def get_user_by_token(self, token):
  133. """ Get a registered user's ID.
  134. Args:
  135. token (str)- The access token to get the user by.
  136. Returns:
  137. UserID : User ID object of the user who has that access token.
  138. Raises:
  139. AuthError if no user by that token exists or the token is invalid.
  140. """
  141. try:
  142. user_id = yield self.store.get_user_by_token(token=token)
  143. defer.returnValue(self.hs.parse_userid(user_id))
  144. except StoreError:
  145. raise AuthError(403, "Unrecognised access token.")