def _activate_preview_language(self, request): """ If the request has the get parameter ``preview-lang``, and that language doesn't appear in ``self.released_langs``, then set the session LANGUAGE_SESSION_KEY to that language. """ if 'clear-lang' in request.GET: # Reset dark lang delete_user_preference(request.user, DARK_LANGUAGE_KEY) # Reset user's language to their language preference, if they have one user_pref = get_user_preference(request.user, LANGUAGE_KEY) if user_pref: request.session[LANGUAGE_SESSION_KEY] = user_pref elif LANGUAGE_SESSION_KEY in request.session: del request.session[LANGUAGE_SESSION_KEY] return preview_lang = request.GET.get('preview-lang', None) if not preview_lang: try: # Try to get the request user's preference (might not have a user, though) preview_lang = get_user_preference(request.user, DARK_LANGUAGE_KEY) except UserNotFound: return if not preview_lang: return request.session[LANGUAGE_SESSION_KEY] = preview_lang set_user_preference(request.user, DARK_LANGUAGE_KEY, preview_lang)
def test_preference_update_noop(self): self.request.COOKIES[settings.LANGUAGE_COOKIE] = 'es' # No preference yet, should write to the database self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), None) self.middleware.process_request(self.request) self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), 'es') response = mock.Mock(spec=HttpResponse) with self.assertNumQueries(1): self.middleware.process_response(self.request, response) # Preference is the same as the cookie, shouldn't write to the database with self.assertNumQueries(3): self.middleware.process_request(self.request) self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), 'es') response = mock.Mock(spec=HttpResponse) with self.assertNumQueries(1): self.middleware.process_response(self.request, response) # Cookie changed, should write to the database again self.request.COOKIES[settings.LANGUAGE_COOKIE] = 'en' self.middleware.process_request(self.request) self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), 'en') with self.assertNumQueries(1): self.middleware.process_response(self.request, response)
def _clear_preview_language(self, request, context): """ Clears the dark language preview Arguments: request (Request): The incoming Django Request context dict: The basic context for the Response Returns: HttpResponse: View containing the form for setting the preview lang with the status included in the context """ # delete the session language key (if one is set) if LANGUAGE_SESSION_KEY in request.session: del request.session[LANGUAGE_SESSION_KEY] user_pref = '' auth_user = request.user if auth_user: # Reset user's dark lang preference to null delete_user_preference(auth_user, DARK_LANGUAGE_KEY) # Get & set user's preferred language user_pref = get_user_preference(auth_user, LANGUAGE_KEY) if user_pref: request.session[LANGUAGE_SESSION_KEY] = user_pref if user_pref is None: message = _('Language reset to the default language code') else: message = _("Language reset to user's preference: {preview_language_code}").format( preview_language_code=user_pref ) context.update({'form_submit_message': message}) context.update({'success': True}) return render_to_response(self.template_name, context)
def send_account_recovery_email_for_user(user, request, email=None): """ Send out a account recovery email for the given user. Arguments: user (User): Django User object request (HttpRequest): Django request object email (str): Send email to this address. """ site = get_current_site() message_context = get_base_template_context(site) message_context.update({ 'request': request, # Used by google_analytics_tracking_pixel 'email': email, 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), 'reset_link': '{protocol}://{site}{link}?is_account_recovery=true'.format( protocol='https' if request.is_secure() else 'http', site=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), link=reverse('password_reset_confirm', kwargs={ 'uidb36': int_to_base36(user.id), 'token': default_token_generator.make_token(user), }), ) }) msg = AccountRecoveryMessage().personalize( recipient=Recipient(user.username, email), language=get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) ace.send(msg)
def send_password_reset_email_for_user(user, request, preferred_email=None): """ Send out a password reset email for the given user. Arguments: user (User): Django User object request (HttpRequest): Django request object preferred_email (str): Send email to this address if present, otherwise fallback to user's email address. """ site = get_current_site() message_context = get_base_template_context(site) message_context.update({ 'request': request, # Used by google_analytics_tracking_pixel # TODO: This overrides `platform_name` from `get_base_template_context` to make the tests passes 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), 'reset_link': '{protocol}://{site}{link}'.format( protocol='https' if request.is_secure() else 'http', site=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), link=reverse('password_reset_confirm', kwargs={ 'uidb36': int_to_base36(user.id), 'token': default_token_generator.make_token(user), }), ) }) msg = PasswordReset().personalize( recipient=Recipient(user.username, preferred_email or user.email), language=get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) ace.send(msg)
def process_response(self, request, response): # If the user is logged in, check for their language preference if getattr(request, 'user', None) and request.user.is_authenticated(): user_pref = None anonymous_cookie_lang = getattr(request, '_anonymous_user_cookie_lang', None) if anonymous_cookie_lang: user_pref = anonymous_cookie_lang set_user_preference(request.user, LANGUAGE_KEY, anonymous_cookie_lang) else: # Get the user's language preference try: user_pref = get_user_preference(request.user, LANGUAGE_KEY) except (UserAPIRequestError, UserAPIInternalError): # If we can't find the user preferences, then don't modify the cookie pass # If set, set the user_pref in the LANGUAGE_COOKIE if user_pref: response.set_cookie( settings.LANGUAGE_COOKIE, value=user_pref, domain=settings.SESSION_COOKIE_DOMAIN, max_age=COOKIE_DURATION, ) else: response.delete_cookie( settings.LANGUAGE_COOKIE, domain=settings.SESSION_COOKIE_DOMAIN ) return response
def set_sharing_preferences(self, user, boolean_value): """ Sets self.user's share settings to boolean_value """ # Note that setting the value to boolean will result in the conversion to the unicode form of the boolean. set_user_preference(user, 'share_with_facebook_friends', boolean_value) self.assertEqual(get_user_preference(user, 'share_with_facebook_friends'), unicode(boolean_value))
def process_request(self, request): """ If a user's UserPreference contains a language preference, use the user's preference. """ languages = released_languages() system_released_languages = [seq[0] for seq in languages] # If the user is logged in, check for their language preference if request.user.is_authenticated(): # Get the user's language preference user_pref = get_user_preference(request.user, LANGUAGE_KEY) # Set it to the LANGUAGE_SESSION_KEY (Django-specific session setting governing language pref) if user_pref: if user_pref in system_released_languages: request.session[LANGUAGE_SESSION_KEY] = user_pref else: delete_user_preference(request.user, LANGUAGE_KEY) else: preferred_language = request.META.get("HTTP_ACCEPT_LANGUAGE", "") lang_headers = [seq[0] for seq in parse_accept_lang_header(preferred_language)] # Setting the session language to the browser language, if it is supported. for browser_lang in lang_headers: if browser_lang in system_released_languages: if request.session.get(LANGUAGE_SESSION_KEY, None) is None: request.session[LANGUAGE_SESSION_KEY] = unicode(browser_lang) break
def test_supported_browser_language_in_session(self): """ test: browser language should be set in user preferences if it is supported by system. """ self.assertEquals(get_user_preference(self.request.user, LANGUAGE_KEY), None) self.middleware.process_request(self.request) self.assertEqual(self.request.session[LANGUAGE_SESSION_KEY], 'ar') # pylint: disable=no-member
def save(self, # pylint: disable=arguments-differ use_https=False, token_generator=default_token_generator, request=None, **_kwargs): """ Generates a one-use only link for resetting password and sends to the user. """ for user in self.users_cache: site = get_current_site() message_context = get_base_template_context(site) message_context.update({ 'request': request, # Used by google_analytics_tracking_pixel # TODO: This overrides `platform_name` from `get_base_template_context` to make the tests passes 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), 'reset_link': '{protocol}://{site}{link}'.format( protocol='https' if use_https else 'http', site=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), link=reverse('password_reset_confirm', kwargs={ 'uidb36': int_to_base36(user.id), 'token': token_generator.make_token(user), }), ) }) msg = PasswordReset().personalize( recipient=Recipient(user.username, user.email), language=get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) ace.send(msg)
def _get_language_preference(self): """ Returns the preferred language for the actual user making the request. """ language_preference = get_user_preference(self.real_user, LANGUAGE_KEY) if not language_preference: language_preference = settings.LANGUAGE_CODE return language_preference
def test_delete_user_lang_preference_not_supported_by_system(self): """ test: user preferred language has been removed from user preferences model if it is not supported by system for authenticated users. """ set_user_preference(self.user, LANGUAGE_KEY, 'eo') self.middleware.process_request(self.request) self.assertEqual(get_user_preference(self.request.user, LANGUAGE_KEY), None)
def test_set_preference_missing_lang(self): user = UserFactory.create() self.client.login(username=user.username, password="******") response = self.client.post(reverse("lang_pref_set_language")) self.assertEquals(response.status_code, 400) self.assertIsNone(get_user_preference(user, LANGUAGE_KEY))
def process_request(self, request): """ If a user's UserPreference contains a language preference and there is no language set on the session (i.e. from dark language overrides), use the user's preference. """ if request.user.is_authenticated() and 'django_language' not in request.session: user_pref = get_user_preference(request.user, LANGUAGE_KEY) if user_pref: request.session['django_language'] = user_pref
def test_discussions_email_digest_pref(self, digest_enabled): with mock.patch.dict("student.models.settings.FEATURES", {"ENABLE_DISCUSSION_EMAIL_DIGEST": digest_enabled}): response = self.client.post(self.url, self.params) self.assertEqual(response.status_code, 200) user = User.objects.get(username=self.username) preference = get_user_preference(user, NOTIFICATION_PREF_KEY) if digest_enabled: self.assertIsNotNone(preference) else: self.assertIsNone(preference)
def _get_language_preference(self): """ Returns the preferred language for the actual user making the request. """ language_preference = settings.LANGUAGE_CODE if self.request.user.is_authenticated: language_preference = get_user_preference(self.real_user, LANGUAGE_KEY) return language_preference
def test_set_preference_happy(self): user = UserFactory.create() self.client.login(username=user.username, password="******") lang = "en" response = self.client.post(reverse("lang_pref_set_language"), {"language": lang}) self.assertEquals(response.status_code, 200) user_pref = get_user_preference(user, LANGUAGE_KEY) self.assertEqual(user_pref, lang)
def get_user_preview_site_theme(request): """ Returns the preview site for the current user, or None if not set. """ user = request.user if not user or user.is_anonymous: return None preview_site_name = get_user_preference(user, PREVIEW_SITE_THEME_PREFERENCE_KEY) if not preview_site_name: return None return SiteTheme(site=request.site, theme_dir_name=preview_site_name)
def process_request(self, request): """ If a user's UserPreference contains a language preference, use the user's preference. """ # If the user is logged in, check for their language preference if request.user.is_authenticated(): # Get the user's language preference user_pref = get_user_preference(request.user, LANGUAGE_KEY) # Set it to the LANGUAGE_SESSION_KEY (Django-specific session setting governing language pref) if user_pref: request.session[LANGUAGE_SESSION_KEY] = user_pref
def test_login_captures_lang_pref(self, lang_cookie, expected_lang): if lang_cookie: self.client.cookies[settings.LANGUAGE_COOKIE] = lang_cookie elif settings.LANGUAGE_COOKIE in self.client.cookies: del self.client.cookies[settings.LANGUAGE_COOKIE] # Use an actual call to the login endpoint, to validate that the middleware # stack does the right thing if settings.FEATURES.get('ENABLE_COMBINED_LOGIN_REGISTRATION'): response = self.client.post( reverse('user_api_login_session'), data={ 'email': self.user.email, 'password': UserFactory._DEFAULT_PASSWORD, 'remember': True, } ) else: response = self.client.post( reverse('login_post'), data={ 'email': self.user.email, 'password': UserFactory._DEFAULT_PASSWORD, 'honor_code': True, } ) self.assertEqual(response.status_code, 200) if lang_cookie: self.assertEqual(response['Content-Language'], expected_lang) self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), lang_cookie) self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE].value, lang_cookie ) else: self.assertEqual(response['Content-Language'], 'en') self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), None) self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE].value, '')
def assertExpectedLanguageInPreference(self, user, expected_language_code): """ This method is a custom assertion verifies that a given user has expected language code in the preference and in cookies. Arguments: user: User model instance expected_language_code: string indicating a language code """ self.assertEqual(get_user_preference(user, LANGUAGE_KEY), expected_language_code) self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE].value, expected_language_code)
def process_request(self, request): """ If a user's UserPreference contains a language preference, use the user's preference. """ ## Mihara: We only expect Russian users for the foreseeable future. ## So we hack out the entire thing by force-setting the preference before this code runs. request.session['django_language'] = 'ru' if request.user.is_authenticated() and 'django_language' not in request.session: user_pref = get_user_preference(request.user, LANGUAGE_KEY) # Set it to the LANGUAGE_SESSION_KEY (Django-specific session setting governing language pref) if user_pref: request.session[LANGUAGE_SESSION_KEY] = user_pref
def _activate_preview_language(self, request): """ If the request has the get parameter ``preview-lang``, and that language doesn't appear in ``self.released_langs``, then set the session LANGUAGE_SESSION_KEY to that language. """ auth_user = request.user.is_authenticated() if 'clear-lang' in request.GET: # delete the session language key (if one is set) if LANGUAGE_SESSION_KEY in request.session: del request.session[LANGUAGE_SESSION_KEY] if auth_user: # Reset user's dark lang preference to null delete_user_preference(request.user, DARK_LANGUAGE_KEY) # Get & set user's preferred language user_pref = get_user_preference(request.user, LANGUAGE_KEY) if user_pref: request.session[LANGUAGE_SESSION_KEY] = user_pref return # Get the user's preview lang - this is either going to be set from a query # param `?preview-lang=xx`, or we may have one already set as a dark lang preference. preview_lang = request.GET.get('preview-lang', None) if not preview_lang and auth_user: # Get the request user's dark lang preference preview_lang = get_user_preference(request.user, DARK_LANGUAGE_KEY) # User doesn't have a dark lang preference, so just return if not preview_lang: return # Set the session key to the requested preview lang request.session[LANGUAGE_SESSION_KEY] = preview_lang # Make sure that we set the requested preview lang as the dark lang preference for the # user, so that the lang_pref middleware doesn't clobber away the dark lang preview. if auth_user: set_user_preference(request.user, DARK_LANGUAGE_KEY, preview_lang)
def process_request(self, request): """ If a user's UserPreference contains a language preference, use the user's preference. """ ## Mihara: We only expect Russian users for the foreseeable future. ## So we hack out the entire thing by force-setting the preference before this code runs. request.session['django_language'] = 'ru' if request.user.is_authenticated( ) and 'django_language' not in request.session: user_pref = get_user_preference(request.user, LANGUAGE_KEY) # Set it to the LANGUAGE_SESSION_KEY (Django-specific session setting governing language pref) if user_pref: request.session[LANGUAGE_SESSION_KEY] = user_pref
def process_request(self, request): languages = released_languages() system_released_languages = [seq[0] for seq in languages] # If the user is logged in, check for their language preference if request.user.is_authenticated(): # Get the user's language preference user_pref = get_user_preference(request.user, LANGUAGE_KEY) # Set it to the LANGUAGE_SESSION_KEY (Django-specific session setting governing language pref) if user_pref: if user_pref in system_released_languages: request.session[LANGUAGE_SESSION_KEY] = user_pref else: delete_user_preference(request.user, LANGUAGE_KEY) else: check = False current_microsite = configuration_helpers.get_value( 'language_code') if current_microsite or current_microsite != '': Language = namedtuple('Language', 'code name') request.session[LANGUAGE_SESSION_KEY] = unicode( current_microsite) check = True if not check: preferred_language = request.META.get('HTTP_ACCEPT_LANGUAGE', '') lang_headers = [ seq[0] for seq in parse_accept_lang_header(preferred_language) ] prefixes = [ prefix.split("-")[0] for prefix in system_released_languages ] # Setting the session language to the browser language, if it is supported. for browser_lang in lang_headers: if browser_lang in system_released_languages: pass elif browser_lang in prefixes: browser_lang = system_released_languages[ prefixes.index(browser_lang)] else: continue if request.session.get(LANGUAGE_SESSION_KEY, None) is None: request.session[LANGUAGE_SESSION_KEY] = unicode( browser_lang) break
def assertExpectedLanguageInPreference(self, user, expected_language_code): """ This method is a custom assertion verifies that a given user has expected language code in the preference and in cookies. Arguments: user: User model instance expected_language_code: string indicating a language code """ self.assertEqual( get_user_preference(user, LANGUAGE_KEY), expected_language_code ) self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE].value, expected_language_code )
def send_course_enrollment_email_for_user(self, site_id, user_id, course_id, message_type): """ Send out a course enrollment email for the given user. Arguments: site_id: Django Site object id user_id: Django User object id course_id: Course id message_type: 'enroll' or 'unenroll' """ site = Site.objects.get(id=site_id) user = User.objects.get(id=user_id) with emulate_http_request(site=site, user=user): course_key = CourseKey.from_string(course_id) course = modulestore().get_course(course_key) request = get_current_request() message_context = get_base_template_context(site) message_context.update({ 'request': request, 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), 'site_name': configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), 'username': user.username, 'course_name': course.display_name, 'course_url': '{protocol}://{site}{link}'.format( protocol='https' if request.is_secure() else 'http', site=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), link=reverse('course_root', kwargs={'course_id': course_id})), }) ace_messages_dict = { 'enroll': CourseEnrollment, 'unenroll': CourseUnenrollment, } message_class = ace_messages_dict[message_type] msg = message_class().personalize( recipient=Recipient(user.username, user.email), language=preferences_api.get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) ace.send(msg)
def _activate_preview_language(self, request): """ Check the user's dark language setting in the session and apply it """ auth_user = request.user.is_authenticated preview_lang = None if auth_user: # Get the request user's dark lang preference preview_lang = get_user_preference(request.user, DARK_LANGUAGE_KEY) # User doesn't have a dark lang preference, so just return if not preview_lang: return # Set the session key to the requested preview lang request.session[LANGUAGE_SESSION_KEY] = preview_lang
def _activate_preview_language(self, request): """ Check the user's dark language setting in the session and apply it """ auth_user = request.user.is_authenticated preview_lang = None if auth_user: # Get the request user's dark lang preference preview_lang = get_user_preference(request.user, DARK_LANGUAGE_KEY) # User doesn't have a dark lang preference, so just return if not preview_lang: return # Set the session key to the requested preview lang request.session[LANGUAGE_SESSION_KEY] = preview_lang
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 send_verification_expiry_email(self, batch_verifications, email_config): """ Sends verification expiry email to the learners in the batch using edx_ace If the email is successfully sent change the expiry_email_date to reflect when the email was sent :param batch_verifications: verification objects for which email will be sent :param email_config: Contains configuration like dry-run flag value, which determines whether actual email will be sent or not """ if email_config['dry_run']: logger.info( u"This was a dry run, no email was sent. For the actual run email would have been sent " u"to {} learner(s)".format(len(batch_verifications)) ) return True site = Site.objects.get_current() message_context = get_base_template_context(site) message_context.update({ 'platform_name': settings.PLATFORM_NAME, 'lms_verification_link': '{}{}'.format(settings.LMS_ROOT_URL, reverse("verify_student_reverify")), 'help_center_link': settings.ID_VERIFICATION_SUPPORT_LINK }) expiry_email = VerificationExpiry(context=message_context) users = User.objects.filter(pk__in=[verification.user_id for verification in batch_verifications]) success = True for verification in batch_verifications: try: user = users.get(pk=verification.user_id) with emulate_http_request(site=site, user=user): msg = expiry_email.personalize( recipient=Recipient(user.username, user.email), language=get_user_preference(user, LANGUAGE_KEY), user_context={ 'full_name': user.profile.name, } ) ace.send(msg) self._set_email_expiry_date(verification, user, email_config) except Exception: # pylint: disable=broad-except logger.exception('Could not send email for verification id %d', verification.id) success = False return success
def process_request(self, request): """ If a user's UserPreference contains a language preference, use the user's preference. """ languages = released_languages() system_released_languages = [seq[0] for seq in languages] # If the user is logged in, check for their language preference if request.user.is_authenticated(): # Get the user's language preference user_pref = get_user_preference(request.user, LANGUAGE_KEY) # Set it to the LANGUAGE_SESSION_KEY (Django-specific session setting governing language pref) if user_pref: if user_pref in system_released_languages: request.session[LANGUAGE_SESSION_KEY] = user_pref else: delete_user_preference(request.user, LANGUAGE_KEY)
def _activate_preview_language(self, request): """ Check the user's dark language setting in the session and apply it """ auth_user = request.user.is_authenticated() preview_lang = None if auth_user: # Get the request user's dark lang preference # Here 'course_lang' param would take priority to get things like xblock translated in specific lang # This change is specifically for translating xblocks in course language preview_lang = request.GET.get("course_lang", get_user_preference(request.user, DARK_LANGUAGE_KEY)) # User doesn't have a dark lang preference, so just return if not preview_lang: return # Set the session key to the requested preview lang request.session[LANGUAGE_SESSION_KEY] = preview_lang
def get_user_timezone_or_last_seen_timezone_or_utc(user): """ Helper method for returning a reasonable timezone for a user. This method returns the timezone in the user's account if that is set. If that is not set, it returns a recent timezone that we have recorded from a user's visit to the courseware. If that is not set or the timezone is unknown, it returns UTC. """ user_timezone = (get_user_preference(user, 'time_zone') or get_last_seen_courseware_timezone(user) or 'UTC') # We have seen non-printable characters (i.e. \x00) showing up in the # user_timezone (I believe via the get_last_seen_courseware_timezone method). # This sanitizes the user_timezone before passing it in. user_timezone = filter(lambda l: l in string.printable, user_timezone) user_timezone = ''.join(user_timezone) try: return timezone(user_timezone) except UnknownTimeZoneError as err: return timezone('UTC')
def send_verification_confirmation_email(context): """Send an email confirming that the user submitted photos for initial verification.""" site = Site.objects.get_current() message_context = get_base_template_context(site) message_context.update(context) user = context['user'] try: with emulate_http_request(site=site, user=user): msg = VerificationSubmitted(context=message_context).personalize( recipient=Recipient(user.id, user.email), language=get_user_preference(user, LANGUAGE_KEY), user_context={'full_name': user.profile.name} ) ace.send(msg) log.info('Verification confirmation email sent to user: %r', user.username) return True except Exception: # pylint: disable=broad-except log.exception('Could not send email for verification confirmation to user %s', user.username) return False
def _activate_preview_language(self, request): """ Check the user's dark language setting in the session and apply it """ auth_user = request.user.is_authenticated preview_lang = None if auth_user: # Get the request user's dark lang preference preview_lang = get_user_preference(request.user, DARK_LANGUAGE_KEY) # Here 'course_lang' param would take priority to get things like xblocks and API response # messages translated in specific language based on the value of this param. preview_lang = request.GET.get("course_lang", preview_lang) # User doesn't have a dark lang preference, so just return if not preview_lang: return # Set the session key to the requested preview lang request.session[LANGUAGE_SESSION_KEY] = preview_lang
def send_verification_expiry_email(batch_verifications, dry_run=False): """ Spins a task to send verification expiry email to the learners in the batch using edx_ace If the email is successfully sent change the expiry_email_date to reflect when the email was sent """ if dry_run: logger.info( u"This was a dry run, no email was sent. For the actual run email would have been sent " u"to {} learner(s)".format(len(batch_verifications))) return site = Site.objects.get_current() message_context = get_base_template_context(site) message_context.update({ 'platform_name': settings.PLATFORM_NAME, 'lms_verification_link': '{}{}'.format(settings.LMS_ROOT_URL, reverse("verify_student_reverify")), 'help_center_link': settings.ID_VERIFICATION_SUPPORT_LINK }) expiry_email = VerificationExpiry(context=message_context) users = User.objects.filter( pk__in=[verification.user_id for verification in batch_verifications]) for verification in batch_verifications: user = users.get(pk=verification.user_id) with emulate_http_request(site=site, user=user): msg = expiry_email.personalize( recipient=Recipient(user.username, user.email), language=get_user_preference(user, LANGUAGE_KEY), user_context={ 'full_name': user.profile.name, }) ace.send(msg) verification_qs = SoftwareSecurePhotoVerification.objects.filter( pk=verification.pk) verification_qs.update(expiry_email_date=datetime.now(UTC))
def send_verification_approved_email(context): """ Sends email to a learner when ID verification has been approved. """ site = Site.objects.get_current() message_context = get_base_template_context(site) message_context.update(context) user = context['user'] try: with emulate_http_request(site=site, user=user): msg = VerificationApproved(context=message_context).personalize( recipient=Recipient(user.id, user.email), language=get_user_preference(user, LANGUAGE_KEY), user_context={'full_name': user.profile.name} ) ace.send(msg) log.info('Verification approved email sent to user: %r', user.username) return True except Exception: # pylint: disable=broad-except log.exception('Could not send email for verification approved to user %s', user.username) return False
def _activate_preview_language(self, request): """ Check the user's dark language setting in the session and apply it """ auth_user = request.user.is_authenticated() preview_lang = None if 'language_default' not in request.session: preview_lang = configuration_helpers.get_value('LANGUAGE_CODE') request.session['language_default'] = preview_lang if auth_user: # Get the request user's dark lang preference preview_lang = get_user_preference(request.user, DARK_LANGUAGE_KEY) # User doesn't have a dark lang preference, so just return if not preview_lang: return # Set the session key to the requested preview lang request.session[LANGUAGE_SESSION_KEY] = preview_lang
def save( self, # pylint: disable=arguments-differ use_https=False, token_generator=default_token_generator, request=None, **_kwargs): """ Generates a one-use only link for resetting password and sends to the user. """ for user in self.users_cache: site = get_current_site() message_context = get_base_template_context(site) message_context.update({ 'request': request, # Used by google_analytics_tracking_pixel # TODO: This overrides `platform_name` from `get_base_template_context` to make the tests passes 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), 'reset_link': '{protocol}://{site}{link}'.format( protocol='https' if use_https else 'http', site=configuration_helpers.get_value( 'SITE_NAME', settings.SITE_NAME), link=reverse('password_reset_confirm', kwargs={ 'uidb36': int_to_base36(user.id), 'token': token_generator.make_token(user), }), ) }) msg = PasswordReset().personalize( recipient=Recipient(user.username, user.email), language=get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) ace.send(msg)
def compose_activation_email(root_url, user, user_registration=None, route_enabled=False, profile_name=''): """ Construct all the required params for the activation email through celery task """ if user_registration is None: user_registration = Registration.objects.get(user=user) message_context = generate_activation_email_context( user, user_registration) message_context.update({ 'confirm_activation_link': '{root_url}/activate/{activation_key}'.format( root_url=root_url, activation_key=message_context['key']), 'route_enabled': route_enabled, 'routed_user': user.username, 'routed_user_email': user.email, 'routed_profile_name': profile_name, }) if route_enabled: dest_addr = settings.FEATURES['REROUTE_ACTIVATION_EMAIL'] else: dest_addr = user.email msg = AccountActivation().personalize( recipient=Recipient(user.username, dest_addr), language=preferences_api.get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) return msg
def send_password_reset_email(self, user, site): """ Send email to learner with reset password link :param user: :param site: """ message_context = get_base_template_context(site) email = user.email if should_redirect_to_authn_microfrontend(): site_url = settings.AUTHN_MICROFRONTEND_URL else: site_url = configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME) message_context.update({ 'email': email, 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), 'reset_link': '{protocol}://{site_url}{link}?track=pwreset'.format( protocol='http', site_url=site_url, link=reverse('password_reset_confirm', kwargs={ 'uidb36': int_to_base36(user.id), 'token': default_token_generator.make_token(user), }), ) }) with emulate_http_request(site, user): msg = PasswordReset().personalize( recipient=Recipient(user.username, email), language=get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) ace.send(msg)
def send_account_recovery_email_for_user(user, request, email=None): """ Send out a account recovery email for the given user. Arguments: user (User): Django User object request (HttpRequest): Django request object email (str): Send email to this address. """ site = get_current_site() message_context = get_base_template_context(site) site_name = settings.LOGISTRATION_MICROFRONTEND_DOMAIN if should_redirect_to_logistration_mircrofrontend() \ else configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME) message_context.update({ 'request': request, # Used by google_analytics_tracking_pixel 'email': email, 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), 'reset_link': '{protocol}://{site}{link}?is_account_recovery=true'.format( protocol='https' if request.is_secure() else 'http', site=site_name, link=reverse('password_reset_confirm', kwargs={ 'uidb36': int_to_base36(user.id), 'token': default_token_generator.make_token(user), }), ) }) msg = AccountRecoveryMessage().personalize( recipient=Recipient(user.username, email), language=get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) ace.send(msg)
def process_response(self, request, response): # If the user is logged in, check for their language preference. Also check for real user # if current user is a masquerading user, user_pref = None current_user = None if hasattr(request, 'user'): current_user = getattr(request.user, 'real_user', request.user) if current_user and current_user.is_authenticated: anonymous_cookie_lang = getattr(request, '_anonymous_user_cookie_lang', None) if anonymous_cookie_lang: user_pref = anonymous_cookie_lang set_user_preference(current_user, LANGUAGE_KEY, anonymous_cookie_lang) else: # Get the user's language preference try: user_pref = get_user_preference(current_user, LANGUAGE_KEY) except (UserAPIRequestError, UserAPIInternalError): # If we can't find the user preferences, then don't modify the cookie pass # If set, set the user_pref in the LANGUAGE_COOKIE if user_pref: if not is_request_from_mobile_app(request): response.set_cookie( settings.LANGUAGE_COOKIE, value=user_pref, domain=settings.SESSION_COOKIE_DOMAIN, max_age=COOKIE_DURATION, ) else: response.delete_cookie(settings.LANGUAGE_COOKIE, domain=settings.SESSION_COOKIE_DOMAIN) return response
def send_verification_expiry_email(batch_verifications, dry_run=False): """ Spins a task to send verification expiry email to the learners in the batch using edx_ace If the email is successfully sent change the expiry_email_date to reflect when the email was sent """ if dry_run: logger.info( u"This was a dry run, no email was sent. For the actual run email would have been sent " u"to {} learner(s)".format(len(batch_verifications)) ) return site = Site.objects.get_current() message_context = get_base_template_context(site) message_context.update({ 'platform_name': settings.PLATFORM_NAME, 'lms_verification_link': '{}{}'.format(settings.LMS_ROOT_URL, reverse("verify_student_reverify")), 'help_center_link': settings.ID_VERIFICATION_SUPPORT_LINK }) expiry_email = VerificationExpiry(context=message_context) users = User.objects.filter(pk__in=[verification.user_id for verification in batch_verifications]) for verification in batch_verifications: user = users.get(pk=verification.user_id) with emulate_http_request(site=site, user=user): msg = expiry_email.personalize( recipient=Recipient(user.username, user.email), language=get_user_preference(user, LANGUAGE_KEY), user_context={ 'full_name': user.profile.name, } ) ace.send(msg) verification_qs = SoftwareSecurePhotoVerification.objects.filter(pk=verification.pk) verification_qs.update(expiry_email_date=now())
def send_password_reset_email_for_user(user, request, preferred_email=None): """ Send out a password reset email for the given user. Arguments: user (User): Django User object request (HttpRequest): Django request object preferred_email (str): Send email to this address if present, otherwise fallback to user's email address. """ site = get_current_site() message_context = get_base_template_context(site) message_context.update({ 'request': request, # Used by google_analytics_tracking_pixel # TODO: This overrides `platform_name` from `get_base_template_context` to make the tests passes 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), 'reset_link': '{protocol}://{site}{link}?track=pwreset'.format( protocol='https' if request.is_secure() else 'http', site=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), link=reverse('password_reset_confirm', kwargs={ 'uidb36': int_to_base36(user.id), 'token': default_token_generator.make_token(user), }), ) }) msg = PasswordReset().personalize( recipient=Recipient(user.username, preferred_email or user.email), language=get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) ace.send(msg)
def process_response(self, request, response): # If the user is logged in, check for their language preference if getattr(request, 'user', None) and request.user.is_authenticated(): # Get the user's language preference try: user_pref = get_user_preference(request.user, LANGUAGE_KEY) except (UserAPIRequestError, UserAPIInternalError): # If we can't find the user preferences, then don't modify the cookie pass else: # Set it in the LANGUAGE_COOKIE if user_pref: response.set_cookie( settings.LANGUAGE_COOKIE, value=user_pref, domain=settings.SESSION_COOKIE_DOMAIN, max_age=COOKIE_DURATION, ) else: response.delete_cookie( settings.LANGUAGE_COOKIE, domain=settings.SESSION_COOKIE_DOMAIN) return response
def process_request(self, request): """ Perform the following checks 1. Check that the user is authenticated and belongs to an enterprise customer. 2. Check that the enterprise customer has a language set via the `default_language` column on EnterpriseCustomer model. 3. Check that user has not set a language via its account settings page. If all the above checks are satisfied then set request._anonymous_user_cookie_lang to the `default_language` of EnterpriseCustomer model instance. This attribute will later be used by the `LanguagePreferenceMiddleware` middleware for setting the user preference. Since, this middleware relies on `LanguagePreferenceMiddleware` so it must always be followed by `LanguagePreferenceMiddleware`. Otherwise, it will not work. """ # If the user is logged in, check for their language preference and user's enterprise configuration. # Also check for real user, if current user is a masquerading user. user_pref, current_user = None, None if hasattr(request, 'user'): current_user = getattr(request.user, 'real_user', request.user) if current_user and current_user.is_authenticated: enterprise_customer = get_enterprise_customer_for_user( current_user) if enterprise_customer and enterprise_customer.default_language: # Get the user's language preference try: user_pref = get_user_preference(current_user, LANGUAGE_KEY) except (UserAPIRequestError, UserAPIInternalError): # Ignore errors related to user preferences not found. pass # If user's language preference is not set and enterprise customer has a default language configured # then set the default language as the learner's language if not user_pref and not is_request_from_mobile_app(request): # pylint: disable=protected-access request._anonymous_user_cookie_lang = enterprise_customer.default_language
def confirm_email_change(request, key): # pylint: disable=unused-argument """ User requested a new e-mail. This is called when the activation link is clicked. We confirm with the old e-mail, and update """ if waffle().is_enabled(PREVENT_AUTH_USER_WRITES): return render_to_response('email_change_failed.html', {'err_msg': SYSTEM_MAINTENANCE_MSG}) with transaction.atomic(): try: pec = PendingEmailChange.objects.get(activation_key=key) except PendingEmailChange.DoesNotExist: response = render_to_response("invalid_email_key.html", {}) transaction.set_rollback(True) return response user = pec.user address_context = { 'old_email': user.email, 'new_email': pec.new_email } if len(User.objects.filter(email=pec.new_email)) != 0: response = render_to_response("email_exists.html", {}) transaction.set_rollback(True) return response use_https = request.is_secure() if settings.FEATURES['ENABLE_MKTG_SITE']: contact_link = marketing_link('CONTACT') else: contact_link = '{protocol}://{site}{link}'.format( protocol='https' if use_https else 'http', site=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), link=reverse('contact'), ) site = Site.objects.get_current() message_context = get_base_template_context(site) message_context.update({ 'old_email': user.email, 'new_email': pec.new_email, 'contact_link': contact_link, 'from_address': configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL), }) msg = EmailChangeConfirmation().personalize( recipient=Recipient(user.username, user.email), language=preferences_api.get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) u_prof = UserProfile.objects.get(user=user) meta = u_prof.get_meta() if 'old_emails' not in meta: meta['old_emails'] = [] meta['old_emails'].append([user.email, datetime.datetime.now(UTC).isoformat()]) u_prof.set_meta(meta) u_prof.save() # Send it to the old email... try: ace.send(msg) except Exception: # pylint: disable=broad-except log.warning('Unable to send confirmation email to old address', exc_info=True) response = render_to_response("email_change_failed.html", {'email': user.email}) transaction.set_rollback(True) return response user.email = pec.new_email user.save() pec.delete() # And send it to the new email... msg.recipient = Recipient(user.username, pec.new_email) try: ace.send(msg) except Exception: # pylint: disable=broad-except log.warning('Unable to send confirmation email to new address', exc_info=True) response = render_to_response("email_change_failed.html", {'email': pec.new_email}) transaction.set_rollback(True) return response response = render_to_response("email_change_successful.html", address_context) return response
def test_header_lang_pref_saved(self, lang): response = self.client.post(self.url, self.params, HTTP_ACCEPT_LANGUAGE=lang) user = User.objects.get(username=self.username) self.assertEqual(response.status_code, 200) self.assertEqual(get_user_preference(user, LANGUAGE_KEY), lang)
def test_default_lang_pref_saved(self, lang): with mock.patch("django.conf.settings.LANGUAGE_CODE", lang): response = self.client.post(self.url, self.params) self.assertEqual(response.status_code, 200) user = User.objects.get(username=self.username) self.assertEqual(get_user_preference(user, LANGUAGE_KEY), lang)
def post(self, request, **kwargs): #from student.forms import send_password_reset_email_for_user from openedx.core.djangoapps.ace_common.template_context import get_base_template_context from openedx.core.djangoapps.theming.helpers import get_current_site from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from student.message_types import PasswordReset from django.contrib.auth.tokens import default_token_generator from django.utils.http import int_to_base36 from edx_ace.recipient import Recipient from openedx.core.djangoapps.user_api.preferences.api import get_user_preference from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY from edx_ace import ace self.data = request.POST.dict() if not ('uservalue' and 'sendotptype' in self.data): return JsonResponse({ "status": 400, "message": "Please enter Valid Mobile Number or Email Address or password", }) if self.data.get('sendotptype') == "mobile": mobile = self.data.get('uservalue') user = User.objects.get(extrafields__phone=mobile) email = user.email else: email = self.data.get('uservalue') if not email: return JsonResponse({ "status": 400, "message": "Email id can not be blank", }) user = User.objects.get(email=email) try: site = get_current_site() message_context = get_base_template_context(site) message_context.update({ 'request': request, # Used by google_analytics_tracking_pixel # TODO: This overrides `platform_name` from `get_base_template_context` to make the tests passes 'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), 'reset_link': '{protocol}://{site}{link}'.format( protocol='https', site=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), link=reverse('password_reset_confirm', kwargs={ 'uidb36': int_to_base36(user.id), 'token': default_token_generator.make_token(user), }), ) }) msg = PasswordReset().personalize( recipient=Recipient(user.username, user.email), language=get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) ace.send(msg) return JsonResponse({ "status": 200, "message": "We sent mail in you email", }) except Exception as e: return JsonResponse({ "status": 400, "message": "Something error in sending mail", "error": "err2", })
def confirm_email_change(request, key): # pylint: disable=unused-argument """ User requested a new e-mail. This is called when the activation link is clicked. We confirm with the old e-mail, and update """ if waffle().is_enabled(PREVENT_AUTH_USER_WRITES): return render_to_response('email_change_failed.html', {'err_msg': SYSTEM_MAINTENANCE_MSG}) with transaction.atomic(): try: pec = PendingEmailChange.objects.get(activation_key=key) except PendingEmailChange.DoesNotExist: response = render_to_response("invalid_email_key.html", {}) transaction.set_rollback(True) return response user = pec.user address_context = {'old_email': user.email, 'new_email': pec.new_email} if len(User.objects.filter(email=pec.new_email)) != 0: response = render_to_response("email_exists.html", {}) transaction.set_rollback(True) return response use_https = request.is_secure() if settings.FEATURES['ENABLE_MKTG_SITE']: contact_link = marketing_link('CONTACT') else: contact_link = '{protocol}://{site}{link}'.format( protocol='https' if use_https else 'http', site=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), link=reverse('contact'), ) site = Site.objects.get_current() message_context = get_base_template_context(site) message_context.update({ 'old_email': user.email, 'new_email': pec.new_email, 'contact_link': contact_link, 'from_address': configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL), }) msg = EmailChangeConfirmation().personalize( recipient=Recipient(user.username, user.email), language=preferences_api.get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) u_prof = UserProfile.objects.get(user=user) meta = u_prof.get_meta() if 'old_emails' not in meta: meta['old_emails'] = [] meta['old_emails'].append( [user.email, datetime.datetime.now(UTC).isoformat()]) u_prof.set_meta(meta) u_prof.save() # Send it to the old email... try: ace.send(msg) except Exception: # pylint: disable=broad-except log.warning('Unable to send confirmation email to old address', exc_info=True) response = render_to_response("email_change_failed.html", {'email': user.email}) transaction.set_rollback(True) return response user.email = pec.new_email user.save() pec.delete() # And send it to the new email... msg.recipient = Recipient(user.username, pec.new_email) try: ace.send(msg) except Exception: # pylint: disable=broad-except log.warning('Unable to send confirmation email to new address', exc_info=True) response = render_to_response("email_change_failed.html", {'email': pec.new_email}) transaction.set_rollback(True) return response response = render_to_response("email_change_successful.html", address_context) return response
def do_email_change_request(user, new_email, activation_key=None, secondary_email_change_request=False): """ Given a new email for a user, does some basic verification of the new address and sends an activation message to the new address. If any issues are encountered with verification or sending the message, a ValueError will be thrown. """ # if activation_key is not passing as an argument, generate a random key if not activation_key: activation_key = uuid.uuid4().hex confirm_link = reverse('confirm_email_change', kwargs={ 'key': activation_key, }) if secondary_email_change_request: PendingSecondaryEmailChange.objects.update_or_create( user=user, defaults={ 'new_secondary_email': new_email, 'activation_key': activation_key, }) confirm_link = reverse('activate_secondary_email', kwargs={'key': activation_key}) else: PendingEmailChange.objects.update_or_create(user=user, defaults={ 'new_email': new_email, 'activation_key': activation_key, }) use_https = theming_helpers.get_current_request().is_secure() site = Site.objects.get_current() message_context = get_base_template_context(site) message_context.update({ 'old_email': user.email, 'new_email': new_email, 'confirm_link': '{protocol}://{site}{link}'.format( protocol='https' if use_https else 'http', site=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), link=confirm_link, ), }) if secondary_email_change_request: msg = RecoveryEmailCreate().personalize( recipient=Recipient(user.username, new_email), language=preferences_api.get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) else: msg = EmailChange().personalize( recipient=Recipient(user.username, new_email), language=preferences_api.get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) try: ace.send(msg) except Exception: from_address = configuration_helpers.get_value( 'email_from_address', settings.DEFAULT_FROM_EMAIL) log.error(u'Unable to send email activation link to user from "%s"', from_address, exc_info=True) raise ValueError( _('Unable to send email activation link. Please try again later.')) if not secondary_email_change_request: # When the email address change is complete, a "edx.user.settings.changed" event will be emitted. # But because changing the email address is multi-step, we also emit an event here so that we can # track where the request was initiated. tracker.emit( SETTING_CHANGE_INITIATED, { "setting": "email", "old": message_context['old_email'], "new": message_context['new_email'], "user_id": user.id, })
def do_email_change_request(user, new_email, activation_key=None, secondary_email_change_request=False): """ Given a new email for a user, does some basic verification of the new address and sends an activation message to the new address. If any issues are encountered with verification or sending the message, a ValueError will be thrown. """ # if activation_key is not passing as an argument, generate a random key if not activation_key: activation_key = uuid.uuid4().hex confirm_link = reverse('confirm_email_change', kwargs={'key': activation_key, }) if secondary_email_change_request: PendingSecondaryEmailChange.objects.update_or_create( user=user, defaults={ 'new_secondary_email': new_email, 'activation_key': activation_key, } ) confirm_link = reverse('activate_secondary_email', kwargs={'key': activation_key}) else: PendingEmailChange.objects.update_or_create( user=user, defaults={ 'new_email': new_email, 'activation_key': activation_key, } ) use_https = theming_helpers.get_current_request().is_secure() site = Site.objects.get_current() message_context = get_base_template_context(site) message_context.update({ 'old_email': user.email, 'new_email': new_email, 'confirm_link': '{protocol}://{site}{link}'.format( protocol='https' if use_https else 'http', site=configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME), link=confirm_link, ), }) if secondary_email_change_request: msg = RecoveryEmailCreate().personalize( recipient=Recipient(user.username, new_email), language=preferences_api.get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) else: msg = EmailChange().personalize( recipient=Recipient(user.username, new_email), language=preferences_api.get_user_preference(user, LANGUAGE_KEY), user_context=message_context, ) try: ace.send(msg) except Exception: from_address = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL) log.error(u'Unable to send email activation link to user from "%s"', from_address, exc_info=True) raise ValueError(_('Unable to send email activation link. Please try again later.')) if not secondary_email_change_request: # When the email address change is complete, a "edx.user.settings.changed" event will be emitted. # But because changing the email address is multi-step, we also emit an event here so that we can # track where the request was initiated. tracker.emit( SETTING_CHANGE_INITIATED, { "setting": "email", "old": message_context['old_email'], "new": message_context['new_email'], "user_id": user.id, } )
def notifications_should_be_disabled(step_): user = User.objects.get(username=USERNAME) assert not get_user_preference(user, NOTIFICATION_PREF_KEY)
def test_default_lang_pref_saved(self, lang): with mock.patch("django.conf.settings.LANGUAGE_CODE", lang): response = self.client.post(self.url, self.params) self.assertEqual(response.status_code, 200) user = User.objects.get(username=self.username) self.assertEqual(get_user_preference(user, LANGUAGE_KEY), lang)
def notifications_should_be_disabled(step_): user = User.objects.get(username=USERNAME) assert not get_user_preference(user, NOTIFICATION_PREF_KEY)
def test_header_lang_pref_saved(self, lang): response = self.client.post(self.url, self.params, HTTP_ACCEPT_LANGUAGE=lang) user = User.objects.get(username=self.username) self.assertEqual(response.status_code, 200) self.assertEqual(get_user_preference(user, LANGUAGE_KEY), lang)
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 = get_learning_mfe_home_url(course_key=goal.course_key, url_fragment='home') goals_unsubscribe_url = f'{settings.LEARNING_MICROFRONTEND_URL}/goal-unsubscribe/{goal.unsubscribe_token}' language = get_user_preference(user, LANGUAGE_KEY) # Code to allow displaying different banner images for different languages # However, we'll likely want to develop a better way to do this within edx-ace image_url = settings.STATIC_URL if image_url: # If the image url is a relative url prepend the LMS ROOT if 'http' not in image_url: image_url = settings.LMS_ROOT_URL + settings.STATIC_URL image_url += 'images/' if language and language in ['es', 'es-419']: image_url += 'spanish-' 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_url, 'goals_unsubscribe_url': goals_unsubscribe_url, 'image_url': image_url, 'unsubscribe_url': None, # We don't want to include the default unsubscribe link 'omit_unsubscribe_link': True, 'courses_url': getattr(settings, 'ACE_EMAIL_COURSES_URL', None), 'programs_url': getattr(settings, 'ACE_EMAIL_PROGRAMS_URL', None), }) msg = Message( name="goalreminder", app_label="course_goals", recipient=Recipient(user.id, user.email), language=language, context=message_context, options={'transactional': True}, ) with emulate_http_request(site, user): ace.send(msg)