Exemple #1
0
    def inner(message, *args, **kwargs):
        try:
            if "method" not in message.content:
                message.content['method'] = "FAKE"
            print("=================", message)
            request = AsgiRequest(message)
        except Exception as e:
            raise ValueError(
                "Cannot parse HTTP message - are you sure this is a HTTP consumer? %s"
                % e)

        token = request.GET.get("token", None)
        print(request.path, request.GET)

        if token is None:
            _close_reply_channel(message)
            raise ValueError(
                "Missing token request parameter. Closing channel.")

        # user, token = token_authenticate(token)
        user, token = token_authenticate(token, message)

        message.token = token
        message.user = user

        return func(message, *args, **kwargs)
Exemple #2
0
 def test_post_multiple(self):
     """
     Tests a POST body across multiple messages (first part in 'body').
     """
     Channel("test").send(
         {
             "reply_channel": "test",
             "http_version": "1.1",
             "method": "POST",
             "path": "/test/",
             "body": b"there_a",
             "body_channel": "test-input",
             "headers": {
                 "host": b"example.com",
                 "content-type": b"application/x-www-form-urlencoded",
                 "content-length": b"21",
             },
         },
         immediately=True)
     Channel("test-input").send(
         {
             "content": b"re=fou",
             "more_content": True,
         }, immediately=True)
     Channel("test-input").send({
         "content": b"r+lights",
     },
                                immediately=True)
     request = AsgiRequest(self.get_next_message("test"))
     self.assertEqual(request.method, "POST")
     self.assertEqual(request.body, b"there_are=four+lights")
     self.assertEqual(request.META["CONTENT_TYPE"],
                      "application/x-www-form-urlencoded")
     self.assertEqual(request.POST["there_are"], "four lights")
Exemple #3
0
    def inner(message, *args, **kwargs):
        # If we didn't get a session, then we don't get a user
        if not hasattr(message, "channel_session"):
            raise ValueError("Did not see a channel session to get auth from")
        if message.channel_session is None:
            # Inner import to avoid reaching into models before load complete
            from django.contrib.auth.models import AnonymousUser
            message.user = AnonymousUser()
            return func(message, *args, **kwargs)
        if message.channel_session.get('user'):
            message.user = message.channel_session['user']
            message.token = message.channel_session['token']
            return func(message, *args, **kwargs)

        # Taken from channels.session.http_session
        try:
            if "method" not in message.content:
                message.content['method'] = "FAKE"
            request = AsgiRequest(message)
        except Exception as e:
            raise ValueError("Cannot parse HTTP message - are you sure this is a HTTP consumer? %s" % e)

        token = request.GET.get("token", None)
        if token is None:
            logger.error("Missing token request parameter. Closing channel.")
            _close_reply_channel(message)
            raise ValueError("Missing token request parameter. Closing channel.")
        user = authenticate(token)
        message.channel_session['token'] = message.token = token
        message.channel_session['user'] = message.user = user
        return func(message, *args, **kwargs)
Exemple #4
0
 def test_basic(self):
     """
     Tests that the handler can decode the most basic request message,
     with all optional fields omitted.
     """
     Channel("test").send(
         {
             "reply_channel": "test-reply",
             "http_version": "1.1",
             "method": "GET",
             "path": "/test/",
         },
         immediately=True)
     request = AsgiRequest(self.get_next_message("test"))
     self.assertEqual(request.path, "/test/")
     self.assertEqual(request.method, "GET")
     self.assertFalse(request.body)
     self.assertNotIn("HTTP_HOST", request.META)
     self.assertNotIn("REMOTE_ADDR", request.META)
     self.assertNotIn("REMOTE_HOST", request.META)
     self.assertNotIn("REMOTE_PORT", request.META)
     self.assertIn("SERVER_NAME", request.META)
     self.assertIn("SERVER_PORT", request.META)
     self.assertFalse(request.GET)
     self.assertFalse(request.POST)
     self.assertFalse(request.COOKIES)
Exemple #5
0
 def test_extended(self):
     """
     Tests a more fully-featured GET request
     """
     Channel("test").send(
         {
             "reply_channel": "test",
             "http_version": "1.1",
             "method": "GET",
             "path": "/test2/",
             "query_string": b"x=1&y=%26foo+bar%2Bbaz",
             "headers": {
                 "host": b"example.com",
                 "cookie": b"test-time=1448995585123; test-value=yeah",
             },
             "client": ["10.0.0.1", 1234],
             "server": ["10.0.0.2", 80],
         },
         immediately=True)
     request = AsgiRequest(self.get_next_message("test"))
     self.assertEqual(request.path, "/test2/")
     self.assertEqual(request.method, "GET")
     self.assertFalse(request.body)
     self.assertEqual(request.META["HTTP_HOST"], "example.com")
     self.assertEqual(request.META["REMOTE_ADDR"], "10.0.0.1")
     self.assertEqual(request.META["REMOTE_HOST"], "10.0.0.1")
     self.assertEqual(request.META["REMOTE_PORT"], 1234)
     self.assertEqual(request.META["SERVER_NAME"], "10.0.0.2")
     self.assertEqual(request.META["SERVER_PORT"], "80")
     self.assertEqual(request.GET["x"], "1")
     self.assertEqual(request.GET["y"], "&foo bar+baz")
     self.assertEqual(request.COOKIES["test-time"], "1448995585123")
     self.assertEqual(request.COOKIES["test-value"], "yeah")
     self.assertFalse(request.POST)
Exemple #6
0
 def test_post_single(self):
     """
     Tests a POST body contained within a single message.
     """
     Channel("test").send(
         {
             "reply_channel": "test",
             "http_version": "1.1",
             "method": "POST",
             "path": "/test2/",
             "query_string": "django=great",
             "body": b"ponies=are+awesome",
             "headers": {
                 "host": b"example.com",
                 "content-type": b"application/x-www-form-urlencoded",
                 "content-length": b"18",
             },
         },
         immediately=True)
     request = AsgiRequest(self.get_next_message("test"))
     self.assertEqual(request.path, "/test2/")
     self.assertEqual(request.method, "POST")
     self.assertEqual(request.body, b"ponies=are+awesome")
     self.assertEqual(request.META["HTTP_HOST"], "example.com")
     self.assertEqual(request.META["CONTENT_TYPE"],
                      "application/x-www-form-urlencoded")
     self.assertEqual(request.GET["django"], "great")
     self.assertEqual(request.POST["ponies"], "are awesome")
     with self.assertRaises(KeyError):
         request.POST["django"]
     with self.assertRaises(KeyError):
         request.GET["ponies"]
def ws_connect(msg):
    request = AsgiRequest(msg)
    request_kwargs = request.GET.dict()

    bridge = BridgeFactory(**request_kwargs)(msg.reply_channel)
    Proxy.session[msg.reply_channel.name] = bridge

    bridge.open(**request_kwargs)
Exemple #8
0
 def connect(self, message, **kwargs):
     request = AsgiRequest(message)
     manual_id = request.GET.get("post", None)
     post = Manual.objects.get(id=manual_id)
     if post:
         print("Connected now to 'post-" + str(post.pk) + "' channel")
         Group("post-{0}".format(post.pk)).add(message.reply_channel)
         self.message.reply_channel.send({"accept": True})
Exemple #9
0
 def connect(self, message, **kwargs):
     request = AsgiRequest(message)
     token = request.GET.get("token", None)
     user = Token.objects.get(key=token).user
     if user:
         Group("notification-{0}".format(user.pk)).add(
             message.reply_channel)
         self.message.reply_channel.send({"accept": True})
Exemple #10
0
 def connect(self, message):
     print("connected")
     print(message.user)
     if not (message.user.is_authenticated
             or check_internal_ip(AsgiRequest(message))):
         self.close()
         return
     data = self._serialize(user=message.user)
     self.send(data)
Exemple #11
0
def my_consumer(message):
    print(('yesdss' + message.handle))
    # response = HttpResponse("Hello world! You asked for %s" % message.content['path'])
    django_request = AsgiRequest(message)
    # Run view
    response = HttpResponse("Hello world! You asked for %s" % message.content['path'])
    # Encode that response into message format (ASGI)
    for chunk in AsgiHandler.encode_response(response):
        message.reply_channel.send(chunk)
Exemple #12
0
 def test_stream(self):
     """
     Tests the body stream is emulated correctly.
     """
     Channel("test").send({
         "reply_channel": "test",
         "http_version": "1.1",
         "method": "PUT",
         "path": "/",
         "body": b"onetwothree",
         "headers": {
             "host": b"example.com",
             "content-length": b"11",
         },
     }, immediately=True)
     request = AsgiRequest(self.get_next_message("test", require=True))
     self.assertEqual(request.method, "PUT")
     self.assertEqual(request.read(3), b"one")
     self.assertEqual(request.read(), b"twothree")
Exemple #13
0
    def inner(message, *args, **kwargs):
        # Make sure there's NOT a http_session already
        try:
            # We want to parse the WebSocket (or similar HTTP-lite) message
            # to get cookies and GET, but we need to add in a few things that
            # might not have been there.
            if "method" not in message.content:
                message.content['method'] = "FAKE"
            request = AsgiRequest(message)

        except Exception as e:
            raise ValueError(
                "Cannot parse HTTP message - are you sure this is a HTTP consumer? %s"
                % e)
        # Make sure there's a session key
        user = None
        auth = None
        auth_token = request.GET.get("token", None)
        print('NEW TOKEN : {}'.format(auth_token))
        if auth_token:
            # comptatibility with rest framework
            request._request = {}
            request.META["HTTP_AUTHORIZATION"] = "Bearer {}".format(auth_token)
            authenticators = [
                auth() for auth in api_settings.DEFAULT_AUTHENTICATION_CLASSES
            ]
            print('Try Auth with {}'.format(
                request.META['HTTP_AUTHORIZATION']))
            for authenticator in authenticators:
                try:
                    user_auth_tuple = authenticator.authenticate(request)
                except AuthenticationFailed:
                    pass

                if user_auth_tuple is not None:
                    message._authenticator = authenticator
                    user, auth = user_auth_tuple
                    break
        message.user, message.auth = user, auth
        # Make sure there's a session key
        # Run the consumer
        result = func(message, *args, **kwargs)
        return result
Exemple #14
0
 def test_stream(self):
     """
     Tests the body stream is emulated correctly.
     """
     message = self.make_message({
         "reply_channel": "test",
         "http_version": "1.1",
         "method": "PUT",
         "path": b"/",
         "body": b"onetwothree",
         "headers": {
             "host": b"example.com",
             "content-length": b"11",
         },
     }, "test")
     request = AsgiRequest(message)
     self.assertEqual(request.method, "PUT")
     self.assertEqual(request.read(3), b"one")
     self.assertEqual(request.read(), b"twothree")
Exemple #15
0
def http_consumer(message):
    #channel_session_user = True
    #http_user = True
    # Decode the request from message format to a Request object
    django_request = AsgiRequest(message)
    # Run view
    django_response = entities(django_request)
    # Encode the response into message format
    for chunk in AsgiHandler.encode_response(django_response):
        message.reply_channel.send(chunk)
Exemple #16
0
 def test_stream(self):
     """
     Tests the body stream is emulated correctly.
     """
     Channel("test").send({
         "reply_channel": "test",
         "http_version": "1.1",
         "method": "PUT",
         "path": b"/",
         "body": b"onetwothree",
         "headers": {
             "host": b"example.com",
             "content-length": b"11",
         },
     })
     request = AsgiRequest(self.get_next_message("test", require=True))
     self.assertEqual(request.method, "PUT")
     self.assertEqual(request.read(3), b"one")
     self.assertEqual(request.read(), b"twothree")
Exemple #17
0
 def request(self):
     if not hasattr(self, "_request"):
         msg = self.message
         connect_content = msg.channel_session.get(self.CONNECT_CONTENT_KEY, None)
         if connect_content is not None:
             msg = msg.copy()
             for k in connect_content.keys():
                 if k not in msg:
                     msg[k] = connect_content[k]
         request = AsgiRequest(msg)
         setattr(self, "_request", request)
     return getattr(self, "_request")
    def inner(message, *args, **kwargs):
        try:
            # We want to parse the WebSocket (or similar HTTP-lite) message
            # to get cookies and GET, but we need to add in a few things that
            # might not have been there.
            if 'method' not in message.content:
                message.content['method'] = 'FAKE'
            request = AsgiRequest(message)

        except Exception as e:
            raise ValueError('Cannot parse HTTP message - are you sure this is a HTTP consumer? {}'.format(e))

        user = None
        auth = None
        auth_token = request.GET.get('token', None)

        if auth_token:
            # comptatibility with rest framework
            request._request = {}
            request.META['HTTP_AUTHORIZATION'] = 'token {}'.format(auth_token)
            for authenticator in authenticators:
                try:
                    user_auth_tuple = authenticator.authenticate(request)
                except AuthenticationFailed:
                    pass

                if user_auth_tuple:
                    message._authenticator = authenticator
                    user, auth = user_auth_tuple
                    break

        if user is not None:
            message.user = user
            message.channel_session['user_id'] = message.user.id
        elif message.channel_session is not None and 'user_id' in message.channel_session:
            message.user = get_user_model().objects.get(id=int(message.channel_session['user_id']))

        # Run the consumer
        result = func(message, *args, **kwargs)
        return result
Exemple #19
0
    def http_handler(self, message, **kwargs):
        """
        Called on HTTP request
        :param message: message received
        :return:
        """
        # Get Django HttpRequest object from ASGI Message
        request = AsgiRequest(message)

        # CORS
        response = CorsMiddleware().process_request(request)
        if not isinstance(response, HttpResponse):

            # Try to process content
            try:
                if request.method != 'POST':
                    raise MethodNotSupported('Only POST method is supported')
                content = request.body.decode('utf-8')
            except (UnicodeDecodeError, MethodNotSupported):
                content = ''
            result, is_notification = self.__handle(content, message, kwargs)

            # Set response status code
            # http://www.jsonrpc.org/historical/json-rpc-over-http.html#response-codes
            if not is_notification:
                # call response
                status_code = 200
                if 'error' in result:
                    code = result['error']['code']
                    status_code = self._http_codes[
                        code] if code in self._http_codes else 500
            else:
                # notification response
                status_code = 204
                if result and 'error' in result:
                    code = result['error']['code']
                    status_code = self._http_codes[
                        code] if code in self._http_codes else 500
                result = ''

            response = HttpResponse(self.__class__._encode(result),
                                    content_type='application/json-rpc',
                                    status=status_code)

        # CORS
        response = CorsMiddleware().process_response(request, response)

        # Encode that response into message format (ASGI)
        for chunk in AsgiHandler.encode_response(response):
            message.reply_channel.send(chunk)
Exemple #20
0
 def connect(self, message, **kwargs):
     try:
         request = AsgiRequest(message)
     except Exception as e:
         self.close()
         return
     token = request.GET.get("token", None)
     if token is None:
         self.close()
         return
     user, token = token_authenticate(token, message)
     message.token = token
     message.user = user
     message.channel_session['user']=user
     self.message.reply_channel.send({"accept": True})
     print('连接状态', message.user)
Exemple #21
0
def ws_connect(message):
    connect_text = {'accept':False, 'user':None}

    message.content['method'] = 'FAKE'
    request = AsgiRequest(message)
    token = request.COOKIES.get('token', None)
    if token is not None:
        token = urllib.unquote(token).strip('"')
        try:
            auth_token = AuthToken.objects.get(key=token)
            if auth_token.in_valid_tokens:
                message.channel_session['user_id'] = auth_token.user_id
                connect_text['accept'] = True
                connect_text['user'] = auth_token.user_id
        except AuthToken.DoesNotExist:
            logger.error("auth_token provided was invalid.")
    message.reply_channel.send({"text": json.dumps(connect_text)})
Exemple #22
0
def ws_connect(message):
    message.reply_channel.send({"accept": True})

    message.content['method'] = 'FAKE'
    request = AsgiRequest(message)
    token = request.COOKIES.get('token', None)
    if token is not None:
        token = urllib.unquote(token).strip('"')
        try:
            auth_token = AuthToken.objects.get(key=token)
            if auth_token.in_valid_tokens:
                message.channel_session['user_id'] = auth_token.user_id
                message.reply_channel.send({"text": json.dumps({"accept": True, "user": auth_token.user_id})})
                return None
        except AuthToken.DoesNotExist:
            logger.error("auth_token provided was invalid.")
    message.reply_channel.send({"close": True})
    return None
Exemple #23
0
    def inner(message, *args, **kwargs):
        # Taken from channels.session.http_session
        # Make sure there's NOT a token_session already
        if hasattr(message, "token_session"):
            return func(message, *args, **kwargs)
        try:
            if "method" not in message.content:
                message.content['method'] = "FAKE"
            request = AsgiRequest(message)
        except Exception as e:
            raise ValueError("Cannot parse HTTP message - are you sure this is a HTTP consumer? %s" % e)

        token = request.GET.get("token", None)
        if token is None:
            # _close_reply_channel(message)
            raise ValueError("Missing token request parameter. Closing channel.")

        message.user = fetch_user_from_token(token)
        message.token = token

        return func(message, *args, **kwargs)
Exemple #24
0
 def connect(self, message, **kwargs):
     """
     Perform things on connection start
     """
     # Accept the connection; this is done by default if you don't override
     # the connect function.
     try:
         request = AsgiRequest(message)
     except Exception as e:
         self.close()
         return
     token = request.GET.get("token", None)
     if token is None:
         self.close()
         return
     user, token = token_authenticate(token, message)
     message.token = token
     message.user = user
     message.channel_session['user'] = user
     self.message.reply_channel.send({"accept": True})
     print '连接状态', message.user
Exemple #25
0
 def test_post_files(self):
     """
     Tests POSTing files using multipart form data and multiple messages,
     with no body in the initial message.
     """
     body = (
         b'--BOUNDARY\r\n' +
         b'Content-Disposition: form-data; name="title"\r\n\r\n' +
         b'My First Book\r\n' + b'--BOUNDARY\r\n' +
         b'Content-Disposition: form-data; name="pdf"; filename="book.pdf"\r\n\r\n'
         + b'FAKEPDFBYTESGOHERE' + b'--BOUNDARY--')
     Channel("test").send(
         {
             "reply_channel": "test",
             "http_version": "1.1",
             "method": "POST",
             "path": "/test/",
             "body_channel": "test-input",
             "headers": {
                 "content-type": b"multipart/form-data; boundary=BOUNDARY",
                 "content-length": six.text_type(len(body)).encode("ascii"),
             },
         },
         immediately=True)
     Channel("test-input").send(
         {
             "content": body[:20],
             "more_content": True,
         }, immediately=True)
     Channel("test-input").send({
         "content": body[20:],
     }, immediately=True)
     request = AsgiRequest(self.get_next_message("test"))
     self.assertEqual(request.method, "POST")
     self.assertEqual(len(request.body), len(body))
     self.assertTrue(
         request.META["CONTENT_TYPE"].startswith("multipart/form-data"))
     self.assertFalse(request._post_parse_error)
     self.assertEqual(request.POST["title"], "My First Book")
     self.assertEqual(request.FILES["pdf"].read(), b"FAKEPDFBYTESGOHERE")
Exemple #26
0
 def test_request_abort(self):
     """
     Tests that the code aborts when a request-body close is sent.
     """
     Channel("test").send({
         "reply_channel": "test",
         "http_version": "1.1",
         "method": "POST",
         "path": b"/test/",
         "body": b"there_a",
         "body_channel": "test-input",
         "headers": {
             "host": b"example.com",
             "content-type": b"application/x-www-form-urlencoded",
             "content-length": b"21",
         },
     })
     Channel("test-input").send({
         "closed": True,
     })
     with self.assertRaises(RequestAborted):
         AsgiRequest(self.get_next_message("test"))
    def inner(message, *args, **kwargs):
        # Taken from channels.session.http_session
        try:
            if "method" not in message.content:
                message.content['method'] = "FAKE"
            request = AsgiRequest(message)
        except Exception as e:
            raise ValueError(
                "Cannot parse HTTP message - are you sure this is a HTTP consumer? %s"
                % e)

        token = request.GET.get("token", None)
        if token is None:
            _close_reply_channel(message)
            raise ValueError(
                "Missing token request parameter. Closing channel.")

        user = authenticate(token)

        message.token = token
        message.user = user

        return func(message, *args, **kwargs)
Exemple #28
0
        def wrapped(req, *args, **kwargs):
            r = view(req, *args, **kwargs)

            if (isinstance(r, HttpResponse)):
                return r

            reply = {
                'status': 200,
                'headers': [
                    ('Content-Type', 'text/event-stream'),
                ],  # we shall probably setup cache headers right as well
                'more_content': True
            }

            if (r):
                group_name = r
            else:
                group_name = self.group_name

            req.message.reply_channel.send(reply)
            Group(group_name).add(req.message.reply_channel)

            # pop !
            raise AsgiRequest.ResponseLater()
Exemple #29
0
    def inner(self, message, *args, **kwargs):
        # Taken from channels.session.http_session
        try:
            if "method" not in message.content:
                message.content['method'] = "FAKE"
            request = AsgiRequest(message)
        except Exception as e:
            raise ValueError("Cannot parse HTTP message - are you sure this is a HTTP consumer? %s" % e)

        key, value = message.content['query_string'].split('=')
        if key != "JWT" or value is None:
            _close_reply_channel(message)
            raise ValueError("Missing token request parameter. Closing channel.")

        token = value
        user = authenticate(token)

        message.token = token
        message.user = user

        self.message.token = token
        self.message.user = user

        return func(self, message, *args, **kwargs)
Exemple #30
0
def ws_connect(message):
    request = AsgiRequest(message)
    session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
    message.channel_session['session_key'] = session_key

    message.reply_channel.send({"text": json.dumps({"status": "connected"})})
Exemple #31
0
 def inner_func(message, *args, **kwargs):
     request = AsgiRequest(message)
     token = request.GET.get("token", None)
     if token is None:
         message.close_reply_channel()
Exemple #32
0
 def consumer(message):
     message.content['method'] = 'FAKE'
     message.reply_channel.send(
         {'text': dict(AsgiRequest(message).GET)})