logout.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # -*- coding: utf-8 -*-
  2. # Copyright 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. import logging
  16. from twisted.internet import defer
  17. from synapse.http.servlet import RestServlet
  18. from synapse.rest.client.v2_alpha._base import client_patterns
  19. logger = logging.getLogger(__name__)
  20. class LogoutRestServlet(RestServlet):
  21. PATTERNS = client_patterns("/logout$", v1=True)
  22. def __init__(self, hs):
  23. super(LogoutRestServlet, self).__init__()
  24. self.auth = hs.get_auth()
  25. self._auth_handler = hs.get_auth_handler()
  26. self._device_handler = hs.get_device_handler()
  27. def on_OPTIONS(self, request):
  28. return (200, {})
  29. @defer.inlineCallbacks
  30. def on_POST(self, request):
  31. requester = yield self.auth.get_user_by_req(request)
  32. if requester.device_id is None:
  33. # the acccess token wasn't associated with a device.
  34. # Just delete the access token
  35. access_token = self.auth.get_access_token_from_request(request)
  36. yield self._auth_handler.delete_access_token(access_token)
  37. else:
  38. yield self._device_handler.delete_device(
  39. requester.user.to_string(), requester.device_id
  40. )
  41. return (200, {})
  42. class LogoutAllRestServlet(RestServlet):
  43. PATTERNS = client_patterns("/logout/all$", v1=True)
  44. def __init__(self, hs):
  45. super(LogoutAllRestServlet, self).__init__()
  46. self.auth = hs.get_auth()
  47. self._auth_handler = hs.get_auth_handler()
  48. self._device_handler = hs.get_device_handler()
  49. def on_OPTIONS(self, request):
  50. return (200, {})
  51. @defer.inlineCallbacks
  52. def on_POST(self, request):
  53. requester = yield self.auth.get_user_by_req(request)
  54. user_id = requester.user.to_string()
  55. # first delete all of the user's devices
  56. yield self._device_handler.delete_all_devices_for_user(user_id)
  57. # .. and then delete any access tokens which weren't associated with
  58. # devices.
  59. yield self._auth_handler.delete_access_tokens_for_user(user_id)
  60. return (200, {})
  61. def register_servlets(hs, http_server):
  62. LogoutRestServlet(hs).register(http_server)
  63. LogoutAllRestServlet(hs).register(http_server)