Exemplo n.º 1
0
    def process_response(self, request, response):
        """
        Inlined and modified from log_request_id.middleware.

        Modified to add more elements to the message, while the request is available.
        """
        if getattr(settings, REQUEST_ID_RESPONSE_HEADER_SETTING,
                   False) and getattr(request, "id", None):
            response[getattr(settings,
                             REQUEST_ID_RESPONSE_HEADER_SETTING)] = request.id

        if not getattr(settings, LOG_REQUESTS_SETTING,
                       False):  # pragma: nocover
            return response

        # Don't log favicon
        if "favicon" in request.path:  # pragma: nocover
            return response

        user = getattr(request, "user", None)
        user_id = getattr(user, "pk", None) or getattr(user, "id", None)
        ip_str = get_remote_ip(request) or "unknown"
        x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")

        message = ("method=%s path=%s status=%s source_ip=%s user_agent=%s"
                   ' time=%s forwardedfor="%s"')
        args = (
            request.method,
            request.path,
            response.status_code,
            ip_str,
            request.META.get("HTTP_USER_AGENT", "unknown"),
            time.time() - local.start_time,
            x_forwarded_for,
        )

        if user_id:
            message += " user=%s"
            args += (user_id, )

        args = [quote_logvalue(v) for v in args]

        logger.info(message, *args)

        try:
            del local.request_id
        except AttributeError:  # pragma: nocover
            pass

        return response
def test_get_remote_ip():
    request = MagicMock()
    request.META = {"HTTP_X_FORWARDED_FOR": "4.4.4.4, 8.8.8.8"}
    assert get_remote_ip(request) == "8.8.8.8"
Exemplo n.º 3
0
    def _validate_ip(self, request):
        ip_str = get_remote_ip(request)
        ip_addr = IPv4Address(ip_str)

        if not any(ip_addr in subnet for subnet in self.ip_ranges):
            raise SuspiciousOperation(f"Disallowed IP address: {ip_addr}")