|
| 1 | +# |
| 2 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 3 | +# VulnerableCode is a trademark of nexB Inc. |
| 4 | +# SPDX-License-Identifier: Apache-2.0 |
| 5 | +# See http://www.apache.org/licenses/LICENSE-2.0 for the license text. |
| 6 | +# See https://github.com/nexB/vulnerablecode for support or download. |
| 7 | +# See https://aboutcode.org for more information about nexB OSS projects. |
| 8 | +# |
| 9 | + |
| 10 | +from django.contrib.auth import get_user_model |
| 11 | +from rest_framework.throttling import UserRateThrottle |
| 12 | + |
| 13 | +User = get_user_model() |
| 14 | + |
| 15 | + |
| 16 | +class ExceptionalUserRateThrottle(UserRateThrottle): |
| 17 | + def allow_request(self, request, view): |
| 18 | + """ |
| 19 | + Give special access to a few special accounts. |
| 20 | +
|
| 21 | + Mirrors code in super class with minor tweaks. |
| 22 | + """ |
| 23 | + if self.rate is None: |
| 24 | + return True |
| 25 | + |
| 26 | + self.key = self.get_cache_key(request, view) |
| 27 | + if self.key is None: |
| 28 | + return True |
| 29 | + |
| 30 | + self.history = self.cache.get(self.key, []) |
| 31 | + self.now = self.timer() |
| 32 | + |
| 33 | + # Adjust if user has special privileges. |
| 34 | + |
| 35 | + user = User.objects.get(username=request.user.username) |
| 36 | + |
| 37 | + if user: |
| 38 | + if user.is_superuser or user.is_staff: |
| 39 | + # No throttling for superusers or staff. |
| 40 | + return True |
| 41 | + |
| 42 | + else: |
| 43 | + self.num_requests = self.num_requests |
| 44 | + self.duration = self.duration |
| 45 | + |
| 46 | + # Drop any requests from the history which have now passed the |
| 47 | + # throttle duration |
| 48 | + while self.history and self.history[-1] <= self.now - self.duration: |
| 49 | + self.history.pop() |
| 50 | + if len(self.history) >= self.num_requests: |
| 51 | + return self.throttle_failure() |
| 52 | + return self.throttle_success() |
0 commit comments