From 136b914d86d485c3a5b3dc4087ba453d67c29bae Mon Sep 17 00:00:00 2001 From: Adeel Khan Date: Mon, 12 Feb 2018 16:41:03 +0500 Subject: [PATCH] Fixes error caused by invalid Anonymous User passed to a view. This patch would fix the case when an anonymous object is getting passed to view causing "TypeError: int() argument must be a string or a number, not 'AnonymousUser'" exception. Applying a permission class would force user to be an authenticated user otherwise would get a 403 response. LEARNER-4162 --- openedx/core/djangoapps/user_api/tests/test_views.py | 12 ++++++++++++ openedx/core/djangoapps/user_api/views.py | 2 ++ 2 files changed, 14 insertions(+) diff --git a/openedx/core/djangoapps/user_api/tests/test_views.py b/openedx/core/djangoapps/user_api/tests/test_views.py index c3673e6977..f993112e33 100644 --- a/openedx/core/djangoapps/user_api/tests/test_views.py +++ b/openedx/core/djangoapps/user_api/tests/test_views.py @@ -2499,6 +2499,18 @@ class UpdateEmailOptInTestCase(UserAPITestCase, SharedModuleStoreTestCase): ) self.assertEquals(preference.value, u"True") + def test_update_email_opt_in_anonymous_user(self): + """ + Test that an anonymous user gets 403 response when + updating email optin preference. + """ + self.client.logout() + response = self.client.post(self.url, { + "course_id": unicode(self.course.id), + "email_opt_in": u"True" + }) + self.assertEqual(response.status_code, 403) + def test_update_email_opt_with_invalid_course_key(self): """ Test that with invalid key it returns bad request diff --git a/openedx/core/djangoapps/user_api/views.py b/openedx/core/djangoapps/user_api/views.py index de05b435a0..628ccbc4a0 100644 --- a/openedx/core/djangoapps/user_api/views.py +++ b/openedx/core/djangoapps/user_api/views.py @@ -14,6 +14,7 @@ from opaque_keys.edx.keys import CourseKey from rest_framework import authentication, generics, status, viewsets from rest_framework.exceptions import ParseError from rest_framework.views import APIView +from rest_framework.permissions import IsAuthenticated from six import text_type import accounts @@ -256,6 +257,7 @@ class PreferenceUsersListView(generics.ListAPIView): class UpdateEmailOptInPreference(APIView): """View for updating the email opt in preference. """ authentication_classes = (SessionAuthenticationAllowInactiveUser,) + permission_classes = (IsAuthenticated,) @method_decorator(require_post_params(["course_id", "email_opt_in"])) @method_decorator(ensure_csrf_cookie)