validator.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  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. from synapse.types import EventID, RoomID, UserID
  16. from synapse.api.errors import SynapseError
  17. from synapse.api.constants import EventTypes, Membership
  18. class EventValidator(object):
  19. def validate(self, event):
  20. EventID.from_string(event.event_id)
  21. RoomID.from_string(event.room_id)
  22. required = [
  23. # "auth_events",
  24. "content",
  25. # "hashes",
  26. "origin",
  27. # "prev_events",
  28. "sender",
  29. "type",
  30. ]
  31. for k in required:
  32. if not hasattr(event, k):
  33. raise SynapseError(400, "Event does not have key %s" % (k,))
  34. # Check that the following keys have string values
  35. strings = [
  36. "origin",
  37. "sender",
  38. "type",
  39. ]
  40. if hasattr(event, "state_key"):
  41. strings.append("state_key")
  42. for s in strings:
  43. if not isinstance(getattr(event, s), basestring):
  44. raise SynapseError(400, "Not '%s' a string type" % (s,))
  45. if event.type == EventTypes.Member:
  46. if "membership" not in event.content:
  47. raise SynapseError(400, "Content has not membership key")
  48. if event.content["membership"] not in Membership.LIST:
  49. raise SynapseError(400, "Invalid membership key")
  50. # Check that the following keys have dictionary values
  51. # TODO
  52. # Check that the following keys have the correct format for DAGs
  53. # TODO
  54. def validate_new(self, event):
  55. self.validate(event)
  56. UserID.from_string(event.sender)
  57. if event.type == EventTypes.Message:
  58. strings = [
  59. "body",
  60. "msgtype",
  61. ]
  62. self._ensure_strings(event.content, strings)
  63. elif event.type == EventTypes.Topic:
  64. self._ensure_strings(event.content, ["topic"])
  65. elif event.type == EventTypes.Name:
  66. self._ensure_strings(event.content, ["name"])
  67. def _ensure_strings(self, d, keys):
  68. for s in keys:
  69. if s not in d:
  70. raise SynapseError(400, "'%s' not in content" % (s,))
  71. if not isinstance(d[s], basestring):
  72. raise SynapseError(400, "Not '%s' a string type" % (s,))