diff --git a/CHANGELOG.md b/CHANGELOG.md index b68cb121..562266bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to - ✨(helm) support celery with our Django backend #1124 - ✨(helm) support ingress for custom background image #1124 +- ✨(backend) add authenticated user rate throttling on request-entry #1129 ### Changed diff --git a/src/backend/core/api/throttling.py b/src/backend/core/api/throttling.py index ecd4304b..b7b89b43 100644 --- a/src/backend/core/api/throttling.py +++ b/src/backend/core/api/throttling.py @@ -3,7 +3,7 @@ from django.conf import settings from lasuite.drf.throttling import MonitoredThrottleMixin -from rest_framework.throttling import AnonRateThrottle +from rest_framework.throttling import AnonRateThrottle, UserRateThrottle from sentry_sdk import capture_message @@ -16,6 +16,24 @@ class MonitoredAnonRateThrottle(MonitoredThrottleMixin, AnonRateThrottle): """Throttle for the monitored scoped rate throttle.""" +class MonitoredUserRateThrottle(MonitoredThrottleMixin, UserRateThrottle): + """Throttle for the monitored scoped rate throttle.""" + + +class RequestEntryAuthenticatedUserRateThrottle(MonitoredUserRateThrottle): + """Throttle authenticated user requesting room entry""" + + scope = "request_entry" + + def get_cache_key(self, request, view): + """Use the authenticated user ID as the throttle cache key.""" + + if request.user and not request.user.is_authenticated: + return None # Defer to RequestEntryAnonRateThrottle for anonymous users. + + return super().get_cache_key(request, view) + + class RequestEntryAnonRateThrottle(MonitoredAnonRateThrottle): """Throttle Anonymous user requesting room entry""" diff --git a/src/backend/core/api/viewsets.py b/src/backend/core/api/viewsets.py index 7a3cad78..8df8492d 100644 --- a/src/backend/core/api/viewsets.py +++ b/src/backend/core/api/viewsets.py @@ -393,7 +393,10 @@ class RoomViewSet( methods=["post"], url_path="request-entry", permission_classes=[], - throttle_classes=[throttling.RequestEntryAnonRateThrottle], + throttle_classes=[ + throttling.RequestEntryAuthenticatedUserRateThrottle, + throttling.RequestEntryAnonRateThrottle, + ], ) def request_entry(self, request, pk=None): # pylint: disable=unused-argument """Request entry to a room"""