Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add throttling to contact api endpoint #1231

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions rdmo/core/assets/js/api/BaseApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ function BadRequestError(errors) {
this.errors = errors
}

function ThrottlingError(errors) {
this.errors = {
throttling: errors.detail
}
}

class BaseApi {

static get(url) {
Expand All @@ -31,6 +37,10 @@ class BaseApi {
return response.json().then(errors => {
throw new BadRequestError(errors)
})
} else if (response.status === 429) {
return response.json().then(errors => {
throw new ThrottlingError(errors)
})
} else {
throw new ApiError(response.statusText, response.status)
}
Expand Down Expand Up @@ -59,6 +69,10 @@ class BaseApi {
return response.json().then(errors => {
throw new ValidationError(errors)
})
} else if (response.status === 429) {
return response.json().then(errors => {
throw new ThrottlingError(errors)
})
} else {
throw new ApiError(response.statusText, response.status)
}
Expand Down
9 changes: 6 additions & 3 deletions rdmo/core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,8 @@

CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'rdmo_default'
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'django_cache'
}
}

Expand All @@ -180,7 +180,10 @@
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
),
'DEFAULT_THROTTLE_RATES': {
'email': '1/minute'
}
}

SETTINGS_EXPORT = [
Expand Down
8 changes: 8 additions & 0 deletions rdmo/core/throttling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from rest_framework.throttling import UserRateThrottle


class EmailThrottle(UserRateThrottle):
scope = 'email'

def allow_request(self, request, view):
return request.method == 'GET' or super().allow_request(request, view)
9 changes: 8 additions & 1 deletion rdmo/projects/assets/js/interview/components/main/Contact.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const Contact = ({ templates, contact, sendContact, closeContact }) => {
bsSize: 'lg'
}}>
<Html html={templates.project_interview_contact_help} />
<form onSubmit={onSubmit}>
<form className="mb-0" onSubmit={onSubmit}>
<div className="form-group">
<label htmlFor="interview-question-contact-subject">Subject</label>
<input
Expand Down Expand Up @@ -66,6 +66,13 @@ const Contact = ({ templates, contact, sendContact, closeContact }) => {
}
</ul>
</div>
{
errors && errors.throttling && (
<ul className="help-block list-unstyled mb-0">
<li className="text-danger">{errors.throttling}</li>
</ul>
)
}
</form>
</Modal>
</>
Expand Down
6 changes: 4 additions & 2 deletions rdmo/projects/tests/test_viewset_project_contact.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@ def test_contact_get_set(db, client):

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_contact_post(db, client, username, password, project_id):
def test_contact_post(db, client,settings, username, password, project_id):
assert settings.PROJECT_CONTACT
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to check this here?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's easier to know what this test is for like that and what the feature flag does..

client.login(username=username, password=password)

url = reverse(urlnames['contact'], args=[project_id])
Expand All @@ -176,7 +177,8 @@ def test_contact_post(db, client, username, password, project_id):

@pytest.mark.parametrize('username,password', users)
@pytest.mark.parametrize('project_id', projects)
def test_contact_post_error(db, client, username, password, project_id):
def test_contact_post_error(db, client,settings, username, password, project_id):
assert settings.PROJECT_CONTACT
client.login(username=username, password=password)

url = reverse(urlnames['contact'], args=[project_id])
Expand Down
12 changes: 9 additions & 3 deletions rdmo/projects/viewsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

from rdmo.conditions.models import Condition
from rdmo.core.permissions import HasModelPermission
from rdmo.core.throttling import EmailThrottle
from rdmo.core.utils import human2bytes, is_truthy, return_file_response
from rdmo.options.models import OptionSet
from rdmo.questions.models import Catalog, Page, Question, QuestionSet
Expand Down Expand Up @@ -329,9 +330,15 @@ def visibility(self, request, pk=None):
raise Http404

@action(detail=True, methods=['get', 'post'],
permission_classes=(HasModelPermission | HasProjectPermission, ))
permission_classes=(HasModelPermission | HasProjectPermission, ),
throttle_classes=[EmailThrottle])
def contact(self, request, pk):
if settings.PROJECT_CONTACT:
try:
project = self.get_object()
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The self.get_object() (permission handling) is needed by the try ... except is not. Since I am not sold on the caching thing yet, I will fix this in the original branch.

except Http404:
return Response(status=status.HTTP_404_NOT_FOUND)

if request.method == 'POST':
subject = request.data.get('subject')
message = request.data.get('message')
Expand All @@ -345,11 +352,10 @@ def contact(self, request, pk):
'message': [_('This field may not be blank.')] if not message else []
})
else:
project = self.get_object()
project.catalog.prefetch_elements()
return Response(get_contact_message(request, project))
else:
return 404
return Response(status=status.HTTP_404_NOT_FOUND)

@action(detail=False, url_path='upload-accept', permission_classes=(IsAuthenticated, ))
def upload_accept(self, request):
Expand Down
Loading