def enroll_and_redirect(request, program_id): """" Enroll and redirect FINAL COURSE """ program = EolCourseProgram.objects.get(pk=program_id) final_course_id = program.final_course_info[ "course_id"] if program.final_course_info else None # get courses list with status => final_course_allowed required to enroll courses_list = _get_courses_list_with_status(request.user, program.courses_list_info) # check if final_course_id is valid try: course_key = CourseKey.from_string(final_course_id) except InvalidKeyError: raise Http404(u"Invalid course_key") if (not _has_access(request, final_course_id) and courses_list["final_course_allowed"]): # enroll as honor student final_course_mode = program.final_course_mode if program.final_course_mode is not None else 'honor' CourseEnrollment.enroll( request.user, course_key, mode=final_course_mode # honor by default ) return redirect( reverse(course_home_url_name(course_key), kwargs={'course_id': final_course_id}))
def test_simple_test(self): """ Simple test to make sure that you don't get a 500 error when the modal is enabled. """ url = reverse(course_home_url_name(self.course.id), args=[self.course.id.to_deprecated_string()]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200)
def test_simple_test(self): """ Simple test to make sure that you don't get a 500 error when the modal is enabled. """ url = reverse(course_home_url_name(self.course.id), args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200)
def send_ace_message(goal): """ Send an email reminding users to stay on track for their learning goal in this course Arguments: goal (CourseGoal): Goal object """ user = goal.user try: course = CourseOverview.get_from_id(goal.course_key) except CourseOverview.DoesNotExist: log.error("Goal Reminder course not found.") course_name = course.display_name site = Site.objects.get_current() message_context = get_base_template_context(site) course_home_url = reverse(course_home_url_name(course.id), args=[str(course.id)]) course_home_absolute_url_parts = ("https", site.name, course_home_url, '', '', '') course_home_absolute_url = six.moves.urllib.parse.urlunparse( course_home_absolute_url_parts) goals_unsubscribe_url = reverse('course-home:unsubscribe-from-course-goal', kwargs={'token': goal.unsubscribe_token}) message_context.update({ 'email': user.email, 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), 'course_name': course_name, 'days_per_week': goal.days_per_week, 'course_url': course_home_absolute_url, 'goals_unsubscribe_url': goals_unsubscribe_url, 'unsubscribe_url': None, # We don't want to include the default unsubscribe link }) msg = Message(name="goalreminder", app_label="course_goals", recipient=Recipient(user.id, user.email), language=get_user_preference(user, LANGUAGE_KEY), context=message_context) with emulate_http_request(site, user): ace.send(msg)
def _get_trackable_course_home_url(course_id): """ Get the home page URL for the course. NOTE: For us to be able to track clicks in the email, this URL needs to point to a landing page that does not result in a redirect so that the GA snippet can register the UTM parameters. Args: course_id (CourseKey): The course to get the home page URL for. Returns: A relative path to the course home page. """ course_url_name = course_home_url_name(course_id) return reverse(course_url_name, args=[str(course_id)])
def _get_trackable_course_home_url(course_id): """ Get the home page URL for the course. NOTE: For us to be able to track clicks in the email, this URL needs to point to a landing page that does not result in a redirect so that the GA snippet can register the UTM parameters. Args: course_id (CourseKey): The course to get the home page URL for. Returns: A relative path to the course home page. """ course_url_name = course_home_url_name(course_id) return reverse(course_url_name, args=[str(course_id)])
def eol_jump_to(request, course_id, location): """ EOL UPDATE: If item not found redirect to course home page Show the page that contains a specific location. If the location is invalid or not in any class, return a 404. Otherwise, delegates to the index view to figure out whether this user has access, and what they should see. """ try: course_key = CourseKey.from_string(course_id) usage_key = UsageKey.from_string(location).replace(course_key=course_key) except InvalidKeyError: raise Http404(u"Invalid course_key or usage_key") try: redirect_url = get_redirect_url(course_key, usage_key, request) except ItemNotFoundError: # If item not found redirect to course home page redirect_url = reverse(course_home_url_name(course_key), kwargs={'course_id': course_id}) except NoPathToItem: raise Http404(u"This location is not in any class: {0}".format(usage_key)) return redirect(redirect_url)
def auto_auth(request): """ Create or configure a user account, then log in as that user. Enabled only when settings.FEATURES['AUTOMATIC_AUTH_FOR_TESTING'] is true. Accepts the following querystring parameters: * `username`, `email`, and `password` for the user account * `full_name` for the user profile (the user's full name; defaults to the username) * `staff`: Set to "true" to make the user global staff. * `course_id`: Enroll the student in the course with `course_id` * `roles`: Comma-separated list of roles to grant the student in the course with `course_id` * `no_login`: Define this to create the user but not login * `redirect`: Set to "true" will redirect to the `redirect_to` value if set, or course home page if course_id is defined, otherwise it will redirect to dashboard * `redirect_to`: will redirect to to this url * `is_active` : make/update account with status provided as 'is_active' If username, email, or password are not provided, use randomly generated credentials. """ # Generate a unique name to use if none provided generated_username = uuid.uuid4().hex[0:30] generated_password = generate_password() # Use the params from the request, otherwise use these defaults username = request.GET.get('username', generated_username) password = request.GET.get('password', generated_password) email = request.GET.get('email', username + "@example.com") full_name = request.GET.get('full_name', username) is_staff = str2bool(request.GET.get('staff', False)) is_superuser = str2bool(request.GET.get('superuser', False)) course_id = request.GET.get('course_id') redirect_to = request.GET.get('redirect_to') is_active = str2bool(request.GET.get('is_active', True)) # Valid modes: audit, credit, honor, no-id-professional, professional, verified enrollment_mode = request.GET.get('enrollment_mode', 'honor') # Parse roles, stripping whitespace, and filtering out empty strings roles = _clean_roles(request.GET.get('roles', '').split(',')) course_access_roles = _clean_roles(request.GET.get('course_access_roles', '').split(',')) redirect_when_done = str2bool(request.GET.get('redirect', '')) or redirect_to login_when_done = 'no_login' not in request.GET form = AccountCreationForm( data={ 'username': username, 'email': email, 'password': password, 'confirm_password': password, 'name': full_name, }, tos_required=False ) # Attempt to create the account. # If successful, this will return a tuple containing # the new user object. try: user, profile, reg = do_create_account(form) except (AccountValidationError, ValidationError): # Attempt to retrieve the existing user. user = User.objects.get(username=username) user.email = email user.set_password(password) user.is_active = is_active user.save() profile = UserProfile.objects.get(user=user) reg = Registration.objects.get(user=user) except PermissionDenied: return HttpResponseForbidden(_('Account creation not allowed.')) user.is_staff = is_staff user.is_superuser = is_superuser user.save() if is_active: reg.activate() reg.save() # ensure parental consent threshold is met year = datetime.date.today().year age_limit = settings.PARENTAL_CONSENT_AGE_LIMIT profile.year_of_birth = (year - age_limit) - 1 profile.save() create_or_set_user_attribute_created_on_site(user, request.site) # Enroll the user in a course course_key = None if course_id: course_key = CourseLocator.from_string(course_id) CourseEnrollment.enroll(user, course_key, mode=enrollment_mode) # Apply the roles for role in roles: assign_role(course_key, user, role) for role in course_access_roles: CourseAccessRole.objects.update_or_create(user=user, course_id=course_key, org=course_key.org, role=role) # Log in as the user if login_when_done: user = authenticate_new_user(request, username, password) django_login(request, user) create_comments_service_user(user) if redirect_when_done: if redirect_to: # Redirect to page specified by the client redirect_url = redirect_to elif course_id: # Redirect to the course homepage (in LMS) or outline page (in Studio) try: redirect_url = reverse(course_home_url_name(course_key), kwargs={'course_id': course_id}) except NoReverseMatch: redirect_url = reverse('course_handler', kwargs={'course_key_string': course_id}) else: # Redirect to the learner dashboard (in LMS) or homepage (in Studio) try: redirect_url = reverse('dashboard') except NoReverseMatch: redirect_url = reverse('home') return redirect(redirect_url) else: response = JsonResponse({ 'created_status': 'Logged in' if login_when_done else 'Created', 'username': username, 'email': email, 'password': password, 'user_id': user.id, # pylint: disable=no-member 'anonymous_id': anonymous_id_for_user(user, None), }) response.set_cookie('csrftoken', csrf(request)['csrf_token']) return response
def auto_auth(request): """ Create or configure a user account, then log in as that user. Enabled only when settings.FEATURES['AUTOMATIC_AUTH_FOR_TESTING'] is true. Accepts the following querystring parameters: * `username`, `email`, and `password` for the user account * `full_name` for the user profile (the user's full name; defaults to the username) * `staff`: Set to "true" to make the user global staff. * `course_id`: Enroll the student in the course with `course_id` * `roles`: Comma-separated list of roles to grant the student in the course with `course_id` * `no_login`: Define this to create the user but not login * `redirect`: Set to "true" will redirect to the `redirect_to` value if set, or course home page if course_id is defined, otherwise it will redirect to dashboard * `redirect_to`: will redirect to to this url * `is_active` : make/update account with status provided as 'is_active' If username, email, or password are not provided, use randomly generated credentials. """ # Generate a unique name to use if none provided generated_username = uuid.uuid4().hex[0:30] generated_password = generate_password() # Use the params from the request, otherwise use these defaults username = request.GET.get('username', generated_username) password = request.GET.get('password', generated_password) email = request.GET.get('email', username + "@example.com") full_name = request.GET.get('full_name', username) is_staff = str2bool(request.GET.get('staff', False)) is_superuser = str2bool(request.GET.get('superuser', False)) course_id = request.GET.get('course_id') redirect_to = request.GET.get('redirect_to') is_active = str2bool(request.GET.get('is_active', True)) # Valid modes: audit, credit, honor, no-id-professional, professional, verified enrollment_mode = request.GET.get('enrollment_mode', 'honor') # Parse roles, stripping whitespace, and filtering out empty strings roles = _clean_roles(request.GET.get('roles', '').split(',')) course_access_roles = _clean_roles(request.GET.get('course_access_roles', '').split(',')) redirect_when_done = str2bool(request.GET.get('redirect', '')) or redirect_to login_when_done = 'no_login' not in request.GET restricted = settings.FEATURES.get('RESTRICT_AUTOMATIC_AUTH', True) if is_superuser and restricted: return HttpResponseForbidden(_('Superuser creation not allowed')) form = AccountCreationForm( data={ 'username': username, 'email': email, 'password': password, 'name': full_name, }, tos_required=False ) # Attempt to create the account. # If successful, this will return a tuple containing # the new user object. try: user, profile, reg = do_create_account(form) except (AccountValidationError, ValidationError): if restricted: return HttpResponseForbidden(_('Account modification not allowed.')) # Attempt to retrieve the existing user. user = User.objects.get(username=username) user.email = email user.set_password(password) user.is_active = is_active user.save() profile = UserProfile.objects.get(user=user) reg = Registration.objects.get(user=user) except PermissionDenied: return HttpResponseForbidden(_('Account creation not allowed.')) user.is_staff = is_staff user.is_superuser = is_superuser user.save() if is_active: reg.activate() reg.save() # ensure parental consent threshold is met year = datetime.date.today().year age_limit = settings.PARENTAL_CONSENT_AGE_LIMIT profile.year_of_birth = (year - age_limit) - 1 profile.save() create_or_set_user_attribute_created_on_site(user, request.site) # Enroll the user in a course course_key = None if course_id: course_key = CourseLocator.from_string(course_id) CourseEnrollment.enroll(user, course_key, mode=enrollment_mode) # Apply the roles for role in roles: assign_role(course_key, user, role) for role in course_access_roles: CourseAccessRole.objects.update_or_create(user=user, course_id=course_key, org=course_key.org, role=role) # Log in as the user if login_when_done: user = authenticate_new_user(request, username, password) django_login(request, user) create_comments_service_user(user) if redirect_when_done: if redirect_to: # Redirect to page specified by the client redirect_url = redirect_to elif course_id: # Redirect to the course homepage (in LMS) or outline page (in Studio) try: redirect_url = reverse(course_home_url_name(course_key), kwargs={'course_id': course_id}) except NoReverseMatch: redirect_url = reverse('course_handler', kwargs={'course_key_string': course_id}) else: # Redirect to the learner dashboard (in LMS) or homepage (in Studio) try: redirect_url = reverse('dashboard') except NoReverseMatch: redirect_url = reverse('home') return redirect(redirect_url) else: response = JsonResponse({ 'created_status': 'Logged in' if login_when_done else 'Created', 'username': username, 'email': email, 'password': password, 'user_id': user.id, # pylint: disable=no-member 'anonymous_id': anonymous_id_for_user(user, None), }) response.set_cookie('csrftoken', csrf(request)['csrf_token']) return response
def location(self, obj): return reverse(course_home_url_name(obj.id), args=[unicode(obj.id)])