From 224331ef5b5a0e98836748f5fcf735598680f9c3 Mon Sep 17 00:00:00 2001 From: Sayyid Hamid Mahdavi Date: Tue, 8 Jul 2025 17:48:15 +0330 Subject: [PATCH] add throttle to request otp APIview --- accounts/settings.py | 7 +++++++ apps/users/views.py | 3 ++- utils/throttles.py | 24 ++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 utils/throttles.py diff --git a/accounts/settings.py b/accounts/settings.py index b9966c6..9acd2cf 100644 --- a/accounts/settings.py +++ b/accounts/settings.py @@ -113,6 +113,13 @@ REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': PAGE_SIZE, "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", + # 'DEFAULT_THROTTLE_CLASSES': [ + # 'rest_framework.throttling.AnonRateThrottle', + # ], + 'DEFAULT_THROTTLE_RATES': { + 'otp_min': '1/min', + 'otp_day': '5/day', + } } SPECTACULAR_SETTINGS = { diff --git a/apps/users/views.py b/apps/users/views.py index e430935..a9b737d 100644 --- a/apps/users/views.py +++ b/apps/users/views.py @@ -19,6 +19,7 @@ from apps.users.models import User from apps.users.provinces_and_cities import State from apps.users.serializers import PublicUserSerializer, AccountSerializer, RequestOTPSerializer, RequestOTTSerializer, \ ChangePasswordSerializer, UserInquirySerializer +from utils.throttles import RequestOTPDayRateThrottle, RequestOTPMinRateThrottle UserModel = get_user_model() @@ -84,7 +85,7 @@ class RequestOTPView(generics.CreateAPIView): permission_classes = [] serializer_class = RequestOTPSerializer required_scopes = [] - + throttle_classes = [RequestOTPMinRateThrottle, RequestOTPDayRateThrottle] class RequestOTTView(generics.CreateAPIView): permission_classes = [IsAuthenticatedOrTokenHasScope] diff --git a/utils/throttles.py b/utils/throttles.py new file mode 100644 index 0000000..33b9e9c --- /dev/null +++ b/utils/throttles.py @@ -0,0 +1,24 @@ +from rest_framework.throttling import SimpleRateThrottle + + +class RequestOTPDayRateThrottle(SimpleRateThrottle): + scope = 'otp_day' + + def get_cache_key(self, request, view): + if request.user and request.user.is_authenticated: + ident = request.user.pk + else: + ident = self.get_ident(request) + + return self.cache_format % { + 'scope': self.scope, + 'ident': ident + } + + +class RequestOTPMinRateThrottle(RequestOTPDayRateThrottle): + scope = 'otp_min' + + + +