diff --git a/lms/djangoapps/sneakpeek_deeplink/__init__.py b/lms/djangoapps/sneakpeek_deeplink/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/lms/djangoapps/sneakpeek_deeplink/middleware.py b/lms/djangoapps/sneakpeek_deeplink/middleware.py new file mode 100644 index 000000000000..002c80f3d0b3 --- /dev/null +++ b/lms/djangoapps/sneakpeek_deeplink/middleware.py @@ -0,0 +1,49 @@ +""" +Middleware class that supports deep-links for allows courses that allow sneakpeek. +The user will be registered anonymously, logged in, and enrolled in the course +""" +from student.models import CourseEnrollment +from util.request import course_id_from_url +from courseware.models import CoursePreference +from student.views import _create_and_login_nonregistered_user, _check_can_enroll_in_course + +class SneakPeekDeepLinkMiddleware(object): + """ + Sneak Peak Deep Link Middlware + """ + def process_request(self, request): + """ + Only if the following are all true: + 1. request.user is AnonymousUser (This middleware must be added after the AuthenticationMiddleware) + 2. request has a course context + 3. request's course allows sneakpeek + 4. request's course's enrollment period is open + Does the following: + 1. Registers an anonymous user + 2. Login this user in + 3. Enrolls this user in the course + """ + ### Start by testing the conditions, each of which can fail fast and return, + ### causing the middleware to do nothing + if request.user.is_authenticated(): + return None + + course_id = course_id_from_url(request.path) + if not course_id: + return None + + if not CoursePreference.course_allows_nonregistered_access(course_id): + return None + + can_enroll, _ = _check_can_enroll_in_course( + request.user, + course_id, + access_type='within_enrollment_period') + + if not can_enroll: + return None + + ### OK. We should now do the 3 steps to get the users access to follow the deeplink + _create_and_login_nonregistered_user(request) + CourseEnrollment.enroll(request.user, course_id) + return None diff --git a/lms/envs/common.py b/lms/envs/common.py index 0f18b5150c5c..d0f9c3dad59f 100644 --- a/lms/envs/common.py +++ b/lms/envs/common.py @@ -732,6 +732,9 @@ #'django.contrib.auth.middleware.AuthenticationMiddleware', 'cache_toolbox.middleware.CacheBackedAuthenticationMiddleware', 'student.middleware.UserStandingMiddleware', + + # sneakpeek deeplinks + 'sneakpeek_deeplink.middleware.SneakPeekDeepLinkMiddleware', 'contentserver.middleware.StaticContentServer', 'crum.CurrentRequestUserMiddleware', @@ -776,6 +779,7 @@ # use Django built in clickjacking protection 'django.middleware.clickjacking.XFrameOptionsMiddleware', + ) # Clickjacking protection can be enabled by setting this to 'DENY' @@ -1199,6 +1203,8 @@ 'reverification', 'embargo', + + 'sneakpeek_deeplink', ) ######################### MARKETING SITE ###############################