def __call__()

in pontoon/base/middleware.py [0:0]


    def __call__(self, request):
        response = self.get_response(request)

        if settings.THROTTLE_ENABLED is False:
            return response

        ip = get_ip(request)

        # Generate cache keys
        observed_key = f"observed_ip_{ip}"
        blocked_key = f"blocked_ip_{ip}"

        # Check if IP is currently blocked
        if cache.get(blocked_key):
            return self._throttle(request)

        # Fetch current request count and timestamp
        request_data = cache.get(observed_key)
        now = time.time()

        if request_data:
            request_count, first_request_time = request_data
            if request_count >= self.max_count:
                user = request.user

                # Do not block IPs of legitimate users
                if user.is_authenticated and user.has_approved_translations:
                    log.info(f"Not blocking IP {ip} of user {user.username}")
                    return response

                # Block further requests for block_duration seconds
                cache.set(blocked_key, True, self.block_duration)
                username = (
                    user.username if user.is_authenticated else "unauthenticated user"
                )
                log.error(
                    f"Blocking IP {ip} of {username} for {self.block_duration} seconds"
                )
                return self._throttle(request)
            else:
                # Increment the request count and update cache
                cache.set(
                    observed_key,
                    (request_count + 1, first_request_time),
                    self.observation_period,
                )
        else:
            # Reset the count and timestamp if first request in the period
            cache.set(observed_key, (1, now), self.observation_period)

        return response