diff --git a/common/djangoapps/student/tests/test_enrollment.py b/common/djangoapps/student/tests/test_enrollment.py index 83fb38a58b..affcdd5598 100644 --- a/common/djangoapps/student/tests/test_enrollment.py +++ b/common/djangoapps/student/tests/test_enrollment.py @@ -142,6 +142,11 @@ class EnrollmentTest(ModuleStoreTestCase): resp = self._change_enrollment('not_an_action') self.assertEqual(resp.status_code, 400) + def test_with_invalid_course_id(self): + CourseEnrollment.enroll(self.user, self.course.id, mode="honor") + resp = self._change_enrollment('unenroll', course_id="edx/") + self.assertEqual(resp.status_code, 400) + def _change_enrollment(self, action, course_id=None, auto_reg=False): """ Change the student's enrollment status in a course. diff --git a/common/djangoapps/student/views.py b/common/djangoapps/student/views.py index 083fca156d..e1bed62c8d 100644 --- a/common/djangoapps/student/views.py +++ b/common/djangoapps/student/views.py @@ -56,6 +56,7 @@ from dark_lang.models import DarkLangConfig from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.modulestore.django import modulestore +from opaque_keys import InvalidKeyError from opaque_keys.edx.locations import SlashSeparatedCourseKey from xmodule.modulestore import ModuleStoreEnum @@ -625,7 +626,13 @@ def change_enrollment(request, auto_register=False): if 'course_id' not in request.POST: return HttpResponseBadRequest(_("Course id not specified")) - course_id = SlashSeparatedCourseKey.from_deprecated_string(request.POST.get("course_id")) + try: + course_id = SlashSeparatedCourseKey.from_deprecated_string(request.POST.get("course_id")) + except InvalidKeyError: + log.warning("User {username} tried to {action} with invalid course id: {course_id}".format( + username=user.username, action=action, course_id=request.POST.get("course_id") + )) + return HttpResponseBadRequest(_("Invalid course id")) if not user.is_authenticated(): return HttpResponseForbidden()