registerservlet.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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 __future__ import absolute_import
  16. from twisted.web.resource import Resource
  17. from twisted.internet import defer
  18. import logging
  19. import json
  20. from six.moves import urllib
  21. from sydent.http.servlets import get_args, jsonwrap, deferjsonwrap, send_cors
  22. from sydent.http.httpclient import FederationHttpClient
  23. from sydent.users.tokens import issueToken
  24. logger = logging.getLogger(__name__)
  25. class RegisterServlet(Resource):
  26. isLeaf = True
  27. def __init__(self, syd):
  28. self.sydent = syd
  29. self.client = FederationHttpClient(self.sydent)
  30. @deferjsonwrap
  31. @defer.inlineCallbacks
  32. def render_POST(self, request):
  33. """
  34. Register with the Identity Server
  35. """
  36. send_cors(request)
  37. args = get_args(request, ('matrix_server_name', 'access_token'))
  38. result = yield self.client.get_json(
  39. "matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s" % (
  40. args['matrix_server_name'], urllib.parse.quote(args['access_token']),
  41. ),
  42. )
  43. if 'sub' not in result:
  44. raise Exception("Invalid response from homeserver")
  45. user_id = result['sub']
  46. tok = yield issueToken(self.sydent, user_id)
  47. # XXX: `token` is correct for the spec, but we released with `access_token`
  48. # for a substantial amount of time. Serve both to make spec-compliant clients
  49. # happy.
  50. defer.returnValue({
  51. "access_token": tok,
  52. "token": tok,
  53. })
  54. def render_OPTIONS(self, request):
  55. send_cors(request)
  56. return b''