Exemplo n.º 1
0
    def zulip_finish(self, result_dict: Dict[str, Any],
                     old_request: HttpRequest, apply_markdown: bool) -> None:
        # Function called when we want to break a long-polled
        # get_events request and return a response to the client.

        # Marshall the response data from result_dict.
        if result_dict[
                'result'] == 'success' and 'messages' in result_dict and apply_markdown:
            for msg in result_dict['messages']:
                if msg['content_type'] != 'text/html':
                    self.set_status(500)
                    self.finish('Internal error: bad message format')
        if result_dict['result'] == 'error':
            self.set_status(400)

        # The `result` dictionary contains the data we want to return
        # to the client.  We want to do so in a proper Tornado HTTP
        # response after running the Django response middleware (which
        # does things like log the request, add rate-limit headers,
        # etc.).  The Django middleware API expects to receive a fresh
        # HttpRequest object, and so to minimize hacks, our strategy
        # is to create a duplicate Django HttpRequest object, tagged
        # to automatically return our data in its response, and call
        # Django's main self.get_response() handler to generate an
        # HttpResponse with all Django middleware run.
        request = self.convert_tornado_request_to_django_request()

        # Add to this new HttpRequest logging data from the processing of
        # the original request; we will need these for logging.
        #
        # TODO: Design a cleaner way to manage these attributes,
        # perhaps via creating a ZulipHttpRequest class that contains
        # these attributes with a copy method.
        request._log_data = old_request._log_data
        if hasattr(request, "_rate_limit"):
            request._rate_limit = old_request._rate_limit
        request._email = old_request._email
        request.user = old_request.user
        request.client = old_request.client

        # The saved_response attribute, if present, causes
        # rest_dispatch to return the response immediately before
        # doing any work.  This arrangement allows Django's full
        # request/middleware system to run unmodified while avoiding
        # running expensive things like Zulip's authentication code a
        # second time.
        request.saved_response = json_response(res_type=result_dict['result'],
                                               data=result_dict,
                                               status=self.get_status())

        try:
            response = self.get_response(request)
        finally:
            # Tell Django we're done processing this request
            #
            # TODO: Investigate whether this (and other call points in
            # this file) should be using response.close() instead.
            signals.request_finished.send(sender=self.__class__)

        self.write_django_response_as_tornado_response(response)
Exemplo n.º 2
0
    def zulip_finish(self, response, request, apply_markdown):
        # type: (HttpResponse, HttpRequest, bool) -> None
        # Make sure that Markdown rendering really happened, if requested.
        # This is a security issue because it's where we escape HTML.
        # c.f. ticket #64
        #
        # apply_markdown=True is the fail-safe default.
        if response[
                'result'] == 'success' and 'messages' in response and apply_markdown:
            for msg in response['messages']:
                if msg['content_type'] != 'text/html':
                    self.set_status(500)
                    self.finish('Internal error: bad message format')
        if response['result'] == 'error':
            self.set_status(400)

        # Call the Django response middleware on our object so that
        # e.g. our own logging code can run; but don't actually use
        # the headers from that since sending those to Tornado seems
        # tricky; instead just send the (already json-rendered)
        # content on to Tornado
        django_response = json_response(res_type=response['result'],
                                        data=response,
                                        status=self.get_status())
        django_response = self.apply_response_middleware(
            request, django_response, request._resolver)
        # Pass through the content-type from Django, as json content should be
        # served as application/json
        self.set_header("Content-Type", django_response['Content-Type'])
        self.finish(django_response.content)
Exemplo n.º 3
0
    def process_exception(self, request: HttpRequest,
                          exception: Exception) -> Optional[HttpResponse]:
        if isinstance(exception, MissingAuthenticationError):
            if "text/html" in request.META.get("HTTP_ACCEPT", ""):
                # If this looks like a request from a top-level page in a
                # browser, send the user to the login page.
                #
                # TODO: The next part is a bit questionable; it will
                # execute the likely intent for intentionally visiting
                # an API endpoint without authentication in a browser,
                # but that's an unlikely to be done intentionally often.
                return HttpResponseRedirect(
                    f"{settings.HOME_NOT_LOGGED_IN}?next={request.path}")
            if request.path.startswith("/api"):
                # For API routes, ask for HTTP basic auth (email:apiKey).
                return json_unauthorized()
            else:
                # For /json routes, ask for session authentication.
                return json_unauthorized(www_authenticate="session")

        if isinstance(exception, JsonableError):
            return json_response_from_error(exception)
        if get_request_notes(request).error_format == "JSON":
            capture_exception(exception)
            json_error_logger = logging.getLogger(
                "zerver.middleware.json_error_handler")
            json_error_logger.error(traceback.format_exc(),
                                    extra=dict(request=request))
            return json_response(res_type="error",
                                 msg=_("Internal server error"),
                                 status=500)
        return None
Exemplo n.º 4
0
    def zulip_finish(self, response, request, apply_markdown):
        # type: (Dict[str, Any], HttpRequest, bool) -> None
        # Make sure that Markdown rendering really happened, if requested.
        # This is a security issue because it's where we escape HTML.
        # c.f. ticket #64
        #
        # apply_markdown=True is the fail-safe default.
        if response['result'] == 'success' and 'messages' in response and apply_markdown:
            for msg in response['messages']:
                if msg['content_type'] != 'text/html':
                    self.set_status(500)
                    self.finish('Internal error: bad message format')
        if response['result'] == 'error':
            self.set_status(400)

        # Call the Django response middleware on our object so that
        # e.g. our own logging code can run; but don't actually use
        # the headers from that since sending those to Tornado seems
        # tricky; instead just send the (already json-rendered)
        # content on to Tornado
        django_response = json_response(res_type=response['result'],
                                        data=response, status=self.get_status())
        django_response = self.apply_response_middleware(request, django_response,
                                                         request._resolver)
        # Pass through the content-type from Django, as json content should be
        # served as application/json
        self.set_header("Content-Type", django_response['Content-Type'])
        self.finish(django_response.content)
Exemplo n.º 5
0
    def zulip_finish(self, result_dict: Dict[str, Any], request: HttpRequest,
                     apply_markdown: bool) -> None:
        # Make sure that Markdown rendering really happened, if requested.
        # This is a security issue because it's where we escape HTML.
        # c.f. ticket #64
        #
        # apply_markdown=True is the fail-safe default.
        if result_dict[
                'result'] == 'success' and 'messages' in result_dict and apply_markdown:
            for msg in result_dict['messages']:
                if msg['content_type'] != 'text/html':
                    self.set_status(500)
                    self.finish('Internal error: bad message format')
        if result_dict['result'] == 'error':
            self.set_status(400)

        # Call the Django response middleware on our object so that
        # e.g. our own logging code can run; but don't actually use
        # the headers from that since sending those to Tornado seems
        # tricky; instead just send the (already json-rendered)
        # content on to Tornado
        django_response = json_response(res_type=result_dict['result'],
                                        data=result_dict,
                                        status=self.get_status())
        django_response = self.apply_response_middleware(
            request, django_response, request._resolver)

        self.write_django_response_as_tornado_response(django_response)
Exemplo n.º 6
0
def stream_exists_backend(request, user_profile, stream_name, autosubscribe):
    if not valid_stream_name(stream_name):
        return json_error("Invalid characters in stream name")
    stream = get_stream(stream_name, user_profile.realm)
    result = {"exists": bool(stream)}
    if stream is not None:
        recipient = get_recipient(Recipient.STREAM, stream.id)
        if autosubscribe:
            bulk_add_subscriptions([stream], [user_profile])
        result["subscribed"] = Subscription.objects.filter(
            user_profile=user_profile, recipient=recipient,
            active=True).exists()
        return json_success(result)  # results are ignored for HEAD requests
    return json_response(data=result, status=404)
Exemplo n.º 7
0
def stream_exists_backend(request, user_profile, stream_name, autosubscribe):
    if not valid_stream_name(stream_name):
        return json_error("Invalid characters in stream name")
    stream = get_stream(stream_name, user_profile.realm)
    result = {"exists": bool(stream)}
    if stream is not None:
        recipient = get_recipient(Recipient.STREAM, stream.id)
        if autosubscribe:
            bulk_add_subscriptions([stream], [user_profile])
        result["subscribed"] = Subscription.objects.filter(user_profile=user_profile,
                                                           recipient=recipient,
                                                           active=True).exists()
        return json_success(result) # results are ignored for HEAD requests
    return json_response(data=result, status=404)
Exemplo n.º 8
0
def stream_exists_backend(request, user_profile, stream_name, autosubscribe):
    # type: (HttpRequest, UserProfile, text_type, bool) -> HttpResponse
    if not valid_stream_name(stream_name):
        return json_error(_("Invalid characters in stream name"))
    stream = get_stream(stream_name, user_profile.realm)
    result = {"exists": bool(stream)}
    if stream is not None:
        recipient = get_recipient(Recipient.STREAM, stream.id)
        if autosubscribe:
            bulk_add_subscriptions([stream], [user_profile])
        result["subscribed"] = is_active_subscriber(user_profile=user_profile,
                                                    recipient=recipient)

        return json_success(result)  # results are ignored for HEAD requests
    return json_response(data=result, status=404)
Exemplo n.º 9
0
def stream_exists_backend(request, user_profile, stream_name, autosubscribe):
    # type: (HttpRequest, UserProfile, text_type, bool) -> HttpResponse
    if not valid_stream_name(stream_name):
        return json_error(_("Invalid characters in stream name"))
    stream = get_stream(stream_name, user_profile.realm)
    result = {"exists": bool(stream)}
    if stream is not None:
        recipient = get_recipient(Recipient.STREAM, stream.id)
        if autosubscribe:
            bulk_add_subscriptions([stream], [user_profile])
        result["subscribed"] = is_active_subscriber(
                user_profile=user_profile,
                recipient=recipient)

        return json_success(result) # results are ignored for HEAD requests
    return json_response(data=result, status=404)
Exemplo n.º 10
0
def stream_exists_backend(request, user_profile, stream_id, autosubscribe):
    # type: (HttpRequest, UserProfile, int, bool) -> HttpResponse
    try:
        stream = get_and_validate_stream_by_id(stream_id, user_profile.realm)
    except JsonableError:
        stream = None
    result = {"exists": bool(stream)}
    if stream is not None:
        recipient = get_recipient(Recipient.STREAM, stream.id)
        if autosubscribe:
            bulk_add_subscriptions([stream], [user_profile])
        result["subscribed"] = is_active_subscriber(user_profile=user_profile,
                                                    recipient=recipient)

        return json_success(result)  # results are ignored for HEAD requests
    return json_response(data=result, status=404)
Exemplo n.º 11
0
def stream_exists_backend(request, user_profile, stream_id, autosubscribe):
    # type: (HttpRequest, UserProfile, int, bool) -> HttpResponse
    try:
        stream = get_and_validate_stream_by_id(stream_id, user_profile.realm)
    except JsonableError:
        stream = None
    result = {"exists": bool(stream)}
    if stream is not None:
        recipient = get_recipient(Recipient.STREAM, stream.id)
        if autosubscribe:
            bulk_add_subscriptions([stream], [user_profile])
        result["subscribed"] = is_active_subscriber(
                user_profile=user_profile,
                recipient=recipient)

        return json_success(result) # results are ignored for HEAD requests
    return json_response(data=result, status=404)
Exemplo n.º 12
0
def delete_group_message(request):
    if request.method != 'DELETE':
        return json_error("Wrong method")
    json_data = simplejson.loads(request.body)
    group_id = json_data['group_id']
    #check ownership of the group
    group = Group.objects.get(id=group_id)
    if (request.user.id != group.owner.id):
        return json_error("You are not the owner of this group")
    #user_id = json_date['user_id']
    try:
        #if user_id > 0:
            #user_profile = UserProfile.objects.get(id=user_id)
        recipient = Recipient.objects.get(type_id=group_id, type=Recipient.GROUP)
    except:
        return json_error("No such group or user")
    messages = Message.objects.filter(recipient=recipient)
    #messages_ids = messages.values('id')
    user_messages = UserMessage.objects.filter(message__in = messages)
    #delete related messages in UserMessage
    user_messages.delete()
    #delete related messages in Message
    messages.delete()
    return json_response(res_type="success", msg="All group messages are deleted!")
Exemplo n.º 13
0
 def test_function(request):
     # type: (HttpRequest) -> HttpResponse
     return json_response(msg=u'from_test_function')  # nocoverage. isn't meant to be called
Exemplo n.º 14
0
    def zulip_finish(self, result_dict: Dict[str, Any],
                     old_request: HttpRequest, apply_markdown: bool) -> None:
        # Function called when we want to break a long-polled
        # get_events request and return a response to the client.

        # Marshall the response data from result_dict.
        if result_dict[
                "result"] == "success" and "messages" in result_dict and apply_markdown:
            for msg in result_dict["messages"]:
                if msg["content_type"] != "text/html":
                    self.set_status(500)
                    self.finish("Internal error: bad message format")
        if result_dict["result"] == "error":
            self.set_status(400)

        # The `result` dictionary contains the data we want to return
        # to the client.  We want to do so in a proper Tornado HTTP
        # response after running the Django response middleware (which
        # does things like log the request, add rate-limit headers,
        # etc.).  The Django middleware API expects to receive a fresh
        # HttpRequest object, and so to minimize hacks, our strategy
        # is to create a duplicate Django HttpRequest object, tagged
        # to automatically return our data in its response, and call
        # Django's main self.get_response() handler to generate an
        # HttpResponse with all Django middleware run.
        request = self.convert_tornado_request_to_django_request()

        # We import RequestNotes during runtime to avoid
        # cyclic import
        from zerver.lib.request import RequestNotes

        request_notes = RequestNotes.get_notes(request)
        old_request_notes = RequestNotes.get_notes(old_request)

        # Add to this new HttpRequest logging data from the processing of
        # the original request; we will need these for logging.
        request_notes.log_data = old_request_notes.log_data
        if request_notes.rate_limit is not None:
            request_notes.rate_limit = old_request_notes.rate_limit
        if request_notes.requestor_for_logs is not None:
            request_notes.requestor_for_logs = old_request_notes.requestor_for_logs
        request.user = old_request.user
        request_notes.client = old_request_notes.client
        request_notes.client_name = old_request_notes.client_name
        request_notes.client_version = old_request_notes.client_version

        # The saved_response attribute, if present, causes
        # rest_dispatch to return the response immediately before
        # doing any work.  This arrangement allows Django's full
        # request/middleware system to run unmodified while avoiding
        # running expensive things like Zulip's authentication code a
        # second time.
        request_notes.saved_response = json_response(
            res_type=result_dict["result"],
            data=result_dict,
            status=self.get_status())

        response = self.get_response(request)
        try:
            # Explicitly mark requests as varying by cookie, since the
            # middleware will not have seen a session access
            patch_vary_headers(response, ("Cookie", ))
            assert isinstance(response, HttpResponse)
            self.write_django_response_as_tornado_response(response)
        finally:
            # Tell Django we're done processing this request
            response.close()
def lookup_endpoints_for_user(request, email=REQ()):
    try:
        return json_response(realm_for_email(email).deployment.endpoints)
    except AttributeError:
        return json_error("Cannot determine endpoint for user.", status=404)
Exemplo n.º 16
0
 def test_function(request):
     # type: (HttpRequest) -> HttpResponse
     return json_response(msg=u'from_test_function')
Exemplo n.º 17
0
 def test_function(request):
     # type: (HttpRequest) -> HttpResponse
     return json_response(msg=u'from_test_function')  # nocoverage. isn't meant to be called
Exemplo n.º 18
0
 def test_function(request):
     # type: (HttpRequest) -> HttpResponse
     return json_response(msg=u'from_test_function')