Example #1
0
    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
Example #2
0
    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
Example #3
0
def index(request):
    """Render the profile info page.

    Args:
        request (HttpRequest)

    Returns:
        HttpResponse: 200 if successful
        HttpResponse: 302 if not logged in (redirect to login page)
        HttpResponse: 405 if using an unsupported HTTP method

    Example:

        GET /profile

    """
    user = request.user

    released_languages = language_api.released_languages()

    preferred_language_code = profile_api.preference_info(user.username).get(LANGUAGE_KEY)
    preferred_language = language_api.preferred_language(preferred_language_code)

    context = {
        'disable_courseware_js': True,
        'released_languages': released_languages,
        'preferred_language': preferred_language,
    }

    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH'):
        context['provider_user_states'] = pipeline.get_provider_user_states(user)

    return render_to_response('student_profile/index.html', context)
Example #4
0
def language_info(request):
    """Retrieve information about languages.

    Gets the user's preferred language and the list of released
    languages, encoding the information as JSON.

    Args:
        request (HttpRequest)

    Returns:
        HttpResponse: 200 if successful on GET
        HttpResponse: 302 if not logged in (redirect to login page)
        HttpResponse: 405 if using an unsupported HTTP method
        HttpResponse: 500 if an unexpected error occurs

    Example:

        GET /profile/preferences/languages

    """
    user = request.user

    preferred_language_code = profile_api.preference_info(user.username).get(LANGUAGE_KEY)
    preferred_language = language_api.preferred_language(preferred_language_code)
    response_data = {'preferredLanguage': {'code': preferred_language.code, 'name': preferred_language.name}}

    languages = language_api.released_languages()
    response_data['languages'] = [{'code': language.code, 'name': language.name} for language in languages]

    return HttpResponse(json.dumps(response_data), content_type='application/json')
Example #5
0
def language_info(request):
    """Retrieve information about languages.

    Gets the user's preferred language and the list of released
    languages, encoding the information as JSON.

    Args:
        request (HttpRequest)

    Returns:
        HttpResponse: 200 if successful on GET
        HttpResponse: 302 if not logged in (redirect to login page)
        HttpResponse: 405 if using an unsupported HTTP method
        HttpResponse: 500 if an unexpected error occurs

    Example:

        GET /profile/preferences/languages

    """
    user = request.user

    preferred_language_code = profile_api.preference_info(user.username).get(LANGUAGE_KEY)
    preferred_language = language_api.preferred_language(preferred_language_code)
    response_data = {'preferredLanguage': {'code': preferred_language.code, 'name': preferred_language.name}}

    languages = language_api.released_languages()
    response_data['languages'] = [{'code': language.code, 'name': language.name} for language in languages]

    return HttpResponse(json.dumps(response_data), content_type='application/json')
def ma_lang_user_preference(user_pref):
    """
        Get a language user preference that is contained in the released LANGUAGES
        or return NONE with which we expect a later instance to decide the language
    """
    released_languages_list = released_languages()
    released_languages_code_list = {langObj.code for langObj in released_languages_list}

    if user_pref not in released_languages_code_list:
        user_pref = None
    return user_pref
Example #7
0
def preference_handler(request):
    """Change the user's preferences.

    At the moment, the only supported preference is the user's
    language choice.

    Args:
        request (HttpRequest)

    Returns:
        HttpResponse: 204 if successful
        HttpResponse: 302 if not logged in (redirect to login page)
        HttpResponse: 400 if no language is provided, or an unreleased
            language is provided
        HttpResponse: 405 if using an unsupported HTTP method
        HttpResponse: 500 if an unexpected error occurs.

    Example:

        PUT /profile/preferences

    """
    put = QueryDict(request.body)

    username = request.user.username
    new_language = put.get('language')

    if new_language is None:
        return HttpResponseBadRequest("Missing param 'language'")

    # Check that the provided language code corresponds to a released language
    released_languages = language_api.released_languages()
    if new_language in [language.code for language in released_languages]:
        try:
            profile_api.update_preferences(username, **{LANGUAGE_KEY: new_language})
            request.session['django_language'] = new_language
        except profile_api.ProfileUserNotFound:
            return HttpResponseServerError()
    else:
        return HttpResponseBadRequest(
            "Provided language code corresponds to an unreleased language"
        )

    # A 204 is intended to allow input for actions to take place
    # without causing a change to the user agent's active document view.
    return HttpResponse(status=204)
Example #8
0
def preference_handler(request):
    """Change the user's preferences.

    At the moment, the only supported preference is the user's
    language choice.

    Args:
        request (HttpRequest)

    Returns:
        HttpResponse: 204 if successful
        HttpResponse: 302 if not logged in (redirect to login page)
        HttpResponse: 400 if no language is provided, or an unreleased
            language is provided
        HttpResponse: 405 if using an unsupported HTTP method
        HttpResponse: 500 if an unexpected error occurs.

    Example:

        PUT /profile/preferences

    """
    put = QueryDict(request.body)

    username = request.user.username
    new_language = put.get('language')

    if new_language is None:
        return HttpResponseBadRequest("Missing param 'language'")

    # Check that the provided language code corresponds to a released language
    released_languages = language_api.released_languages()
    if new_language in [language.code for language in released_languages]:
        try:
            profile_api.update_preferences(username,
                                           **{LANGUAGE_KEY: new_language})
            request.session['django_language'] = new_language
        except profile_api.ProfileUserNotFound:
            return HttpResponseServerError()
    else:
        return HttpResponseBadRequest(
            "Provided language code corresponds to an unreleased language")

    # A 204 is intended to allow input for actions to take place
    # without causing a change to the user agent's active document view.
    return HttpResponse(status=204)
Example #9
0
def index(request):
    """Render the profile info page.

    Args:
        request (HttpRequest)

    Returns:
        HttpResponse: 200 if successful
        HttpResponse: 302 if not logged in (redirect to login page)
        HttpResponse: 405 if using an unsupported HTTP method

    Example:

        GET /profile

    """
    user = request.user

    released_languages = language_api.released_languages()

    preferred_language_code = profile_api.preference_info(
        user.username).get(LANGUAGE_KEY)
    preferred_language = language_api.preferred_language(
        preferred_language_code)

    context = {
        'disable_courseware_js': True,
        'released_languages': released_languages,
        'preferred_language': preferred_language,
    }

    if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH'):
        context['provider_user_states'] = pipeline.get_provider_user_states(
            user)

    return render_to_response('student_profile/index.html', context)
Example #10
0
def account_settings_context(request):
    """ Context for the account settings page.

    Args:
        request: The request object.

    Returns:
        dict

    """
    user = request.user

    year_of_birth_options = [(unicode(year), unicode(year)) for year in UserProfile.VALID_YEARS]
    try:
        user_orders = get_user_orders(user)
    except:  # pylint: disable=bare-except
        log.exception('Error fetching order history from Otto.')
        # Return empty order list as account settings page expect a list and
        # it will be broken if exception raised
        user_orders = []

    context = {
        'auth': {},
        'duplicate_provider': None,
        'nav_hidden': True,
        'fields': {
            'country': {
                'options': list(countries),
            }, 'gender': {
                'options': [(choice[0], _(choice[1])) for choice in UserProfile.GENDER_CHOICES],  # pylint: disable=translation-of-non-string
            }, 'language': {
                'options': released_languages(),
            }, 'level_of_education': {
                'options': [(choice[0], _(choice[1])) for choice in UserProfile.LEVEL_OF_EDUCATION_CHOICES],  # pylint: disable=translation-of-non-string
            }, 'password': {
                'url': reverse('password_reset'),
            }, 'year_of_birth': {
                'options': year_of_birth_options,
            }, 'preferred_language': {
                'options': all_languages(),
            }, 'time_zone': {
                'options': TIME_ZONE_CHOICES,
            }
        },
        'platform_name': configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME),
        'user_accounts_api_url': reverse("accounts_api", kwargs={'username': user.username}),
        'user_preferences_api_url': reverse('preferences_api', kwargs={'username': user.username}),
        'disable_courseware_js': True,
        'show_program_listing': ProgramsApiConfig.current().show_program_listing,
        'order_history': user_orders
    }

    if third_party_auth.is_enabled():
        # If the account on the third party provider is already connected with another edX account,
        # we display a message to the user.
        context['duplicate_provider'] = pipeline.get_duplicate_provider(messages.get_messages(request))

        auth_states = pipeline.get_provider_user_states(user)

        context['auth']['providers'] = [{
            'id': state.provider.provider_id,
            'name': state.provider.name,  # The name of the provider e.g. Facebook
            'connected': state.has_account,  # Whether the user's edX account is connected with the provider.
            # If the user is not connected, they should be directed to this page to authenticate
            # with the particular provider, as long as the provider supports initiating a login.
            'connect_url': pipeline.get_login_url(
                state.provider.provider_id,
                pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS,
                # The url the user should be directed to after the auth process has completed.
                redirect_url=reverse('account_settings'),
            ),
            'accepts_logins': state.provider.accepts_logins,
            # If the user is connected, sending a POST request to this url removes the connection
            # information for this provider from their edX account.
            'disconnect_url': pipeline.get_disconnect_url(state.provider.provider_id, state.association_id),
        } for state in auth_states]

    return context
Example #11
0
def account_settings_context(request):
    """ Context for the account settings page.

    Args:
        request: The request object.

    Returns:
        dict

    """
    user = request.user

    country_options = [
        (country_code, _(country_name))  # pylint: disable=translation-of-non-string
        for country_code, country_name in sorted(countries.countries, key=lambda (__, name): unicode(name))
    ]

    year_of_birth_options = [(unicode(year), unicode(year)) for year in UserProfile.VALID_YEARS]

    context = {
        "auth": {},
        "duplicate_provider": None,
        "fields": {
            "country": {"options": country_options},
            "gender": {
                "options": [
                    (choice[0], _(choice[1])) for choice in UserProfile.GENDER_CHOICES
                ]  # pylint: disable=translation-of-non-string
            },
            "language": {"options": released_languages()},
            "level_of_education": {
                "options": [
                    (choice[0], _(choice[1])) for choice in UserProfile.LEVEL_OF_EDUCATION_CHOICES
                ]  # pylint: disable=translation-of-non-string
            },
            "password": {"url": reverse("password_reset")},
            "year_of_birth": {"options": year_of_birth_options},
            "preferred_language": {"options": settings.ALL_LANGUAGES},
        },
        "platform_name": settings.PLATFORM_NAME,
        "user_accounts_api_url": reverse("accounts_api", kwargs={"username": user.username}),
        "user_preferences_api_url": reverse("preferences_api", kwargs={"username": user.username}),
    }

    if third_party_auth.is_enabled():
        # If the account on the third party provider is already connected with another edX account,
        # we display a message to the user.
        context["duplicate_provider"] = pipeline.get_duplicate_provider(messages.get_messages(request))

        auth_states = pipeline.get_provider_user_states(user)

        context["auth"]["providers"] = [
            {
                "name": state.provider.NAME,  # The name of the provider e.g. Facebook
                "connected": state.has_account,  # Whether the user's edX account is connected with the provider.
                # If the user is not connected, they should be directed to this page to authenticate
                # with the particular provider.
                "connect_url": pipeline.get_login_url(
                    state.provider.NAME,
                    pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS,
                    # The url the user should be directed to after the auth process has completed.
                    redirect_url=reverse("account_settings"),
                ),
                # If the user is connected, sending a POST request to this url removes the connection
                # information for this provider from their edX account.
                "disconnect_url": pipeline.get_disconnect_url(state.provider.NAME),
            }
            for state in auth_states
        ]

    try:
        external_auth_map = ExternalAuthMap.objects.get(user=user)
    except:
        external_auth_map = None
    context["is_shib_auth"] = "shib" in external_auth_map.external_domain if external_auth_map else False

    return context
Example #12
0
def account_settings_context(request):
    """ Context for the account settings page.

    Args:
        request: The request object.

    Returns:
        dict

    """
    user = request.user

    year_of_birth_options = [(unicode(year), unicode(year))
                             for year in UserProfile.VALID_YEARS]

    context = {
        'auth': {},
        'duplicate_provider':
        None,
        'fields': {
            'country': {
                'options': list(countries),
            },
            'gender': {
                'options': [(choice[0], _(choice[1]))
                            for choice in UserProfile.GENDER_CHOICES],  # pylint: disable=translation-of-non-string
            },
            'language': {
                'options': released_languages(),
            },
            'level_of_education': {
                'options':
                [(choice[0], _(choice[1]))
                 for choice in UserProfile.LEVEL_OF_EDUCATION_CHOICES],  # pylint: disable=translation-of-non-string
            },
            'password': {
                'url': reverse('password_reset'),
            },
            'year_of_birth': {
                'options': year_of_birth_options,
            },
            'preferred_language': {
                'options': settings.ALL_LANGUAGES,
            }
        },
        'platform_name':
        settings.PLATFORM_NAME,
        'user_accounts_api_url':
        reverse("accounts_api", kwargs={'username': user.username}),
        'user_preferences_api_url':
        reverse('preferences_api', kwargs={'username': user.username}),
    }

    if third_party_auth.is_enabled():
        # If the account on the third party provider is already connected with another edX account,
        # we display a message to the user.
        context['duplicate_provider'] = pipeline.get_duplicate_provider(
            messages.get_messages(request))

        auth_states = pipeline.get_provider_user_states(user)

        context['auth']['providers'] = [
            {
                'id':
                state.provider.provider_id,
                'name':
                state.provider.name,  # The name of the provider e.g. Facebook
                'connected':
                state.
                has_account,  # Whether the user's edX account is connected with the provider.
                # If the user is not connected, they should be directed to this page to authenticate
                # with the particular provider.
                'connect_url':
                pipeline.get_login_url(
                    state.provider.provider_id,
                    pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS,
                    # The url the user should be directed to after the auth process has completed.
                    redirect_url=reverse('account_settings'),
                ),
                # If the user is connected, sending a POST request to this url removes the connection
                # information for this provider from their edX account.
                'disconnect_url':
                pipeline.get_disconnect_url(state.provider.provider_id,
                                            state.association_id),
            } for state in auth_states
        ]

    return context
Example #13
0
def account_settings_context(request):
    """ Context for the account settings page.

    Args:
        request: The request object.

    Returns:
        dict

    """
    user = request.user

    year_of_birth_options = [(unicode(year), unicode(year)) for year in UserProfile.VALID_YEARS]

    context = {
        "auth": {},
        "duplicate_provider": None,
        "fields": {
            "country": {"options": list(countries)},
            "gender": {
                "options": [
                    (choice[0], _(choice[1])) for choice in UserProfile.GENDER_CHOICES
                ]  # pylint: disable=translation-of-non-string
            },
            "language": {"options": released_languages()},
            "level_of_education": {
                "options": [
                    (choice[0], _(choice[1])) for choice in UserProfile.LEVEL_OF_EDUCATION_CHOICES
                ]  # pylint: disable=translation-of-non-string
            },
            "password": {"url": reverse("password_reset")},
            "year_of_birth": {"options": year_of_birth_options},
            "preferred_language": {"options": settings.ALL_LANGUAGES},
        },
        "platform_name": settings.PLATFORM_NAME,
        "user_accounts_api_url": reverse("accounts_api", kwargs={"username": user.username}),
        "user_preferences_api_url": reverse("preferences_api", kwargs={"username": user.username}),
        "disable_courseware_js": True,
    }

    if third_party_auth.is_enabled():
        # If the account on the third party provider is already connected with another edX account,
        # we display a message to the user.
        context["duplicate_provider"] = pipeline.get_duplicate_provider(messages.get_messages(request))

        auth_states = pipeline.get_provider_user_states(user)

        context["auth"]["providers"] = [
            {
                "id": state.provider.provider_id,
                "name": state.provider.name,  # The name of the provider e.g. Facebook
                "connected": state.has_account,  # Whether the user's edX account is connected with the provider.
                # If the user is not connected, they should be directed to this page to authenticate
                # with the particular provider, as long as the provider supports initiating a login.
                "connect_url": pipeline.get_login_url(
                    state.provider.provider_id,
                    pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS,
                    # The url the user should be directed to after the auth process has completed.
                    redirect_url=reverse("account_settings"),
                ),
                "accepts_logins": state.provider.accepts_logins,
                # If the user is connected, sending a POST request to this url removes the connection
                # information for this provider from their edX account.
                "disconnect_url": pipeline.get_disconnect_url(state.provider.provider_id, state.association_id),
            }
            for state in auth_states
        ]

    return context
Example #14
0
 def test_released_languages(self):
     released_languages = language_api.released_languages()
     self.assertGreaterEqual(len(released_languages), 1)
Example #15
0
 def test_released_languages(self):
     released_languages = language_api.released_languages()
     self.assertGreaterEqual(len(released_languages), 1)
Example #16
0
def account_settings_context(request):
    """ Context for the account settings page.

    Args:
        request: The request object.

    Returns:
        dict

    """
    user = request.user

    year_of_birth_options = [(unicode(year), unicode(year)) for year in UserProfile.VALID_YEARS]

    context = {
        'auth': {},
        'duplicate_provider': None,
        'fields': {
            'country': {
                'options': list(countries),
            }, 'gender': {
                'options': [(choice[0], _(choice[1])) for choice in UserProfile.GENDER_CHOICES],  # pylint: disable=translation-of-non-string
            }, 'language': {
                'options': released_languages(),
            }, 'level_of_education': {
                'options': [(choice[0], _(choice[1])) for choice in UserProfile.LEVEL_OF_EDUCATION_CHOICES],  # pylint: disable=translation-of-non-string
            }, 'password': {
                'url': reverse('password_reset'),
            }, 'year_of_birth': {
                'options': year_of_birth_options,
            }, 'preferred_language': {
                'options': settings.ALL_LANGUAGES,
            }
        },
        'platform_name': settings.PLATFORM_NAME,
        'user_accounts_api_url': reverse("accounts_api", kwargs={'username': user.username}),
        'user_preferences_api_url': reverse('preferences_api', kwargs={'username': user.username}),
        'disable_courseware_js': True,
    }

    if third_party_auth.is_enabled():
        # If the account on the third party provider is already connected with another edX account,
        # we display a message to the user.
        context['duplicate_provider'] = pipeline.get_duplicate_provider(messages.get_messages(request))

        auth_states = pipeline.get_provider_user_states(user)

        context['auth']['providers'] = [{
            'id': state.provider.provider_id,
            'name': state.provider.name,  # The name of the provider e.g. Facebook
            'connected': state.has_account,  # Whether the user's edX account is connected with the provider.
            # If the user is not connected, they should be directed to this page to authenticate
            # with the particular provider.
            'connect_url': pipeline.get_login_url(
                state.provider.provider_id,
                pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS,
                # The url the user should be directed to after the auth process has completed.
                redirect_url=reverse('account_settings'),
            ),
            # If the user is connected, sending a POST request to this url removes the connection
            # information for this provider from their edX account.
            'disconnect_url': pipeline.get_disconnect_url(state.provider.provider_id, state.association_id),
        } for state in auth_states]

    return context
Example #17
0
def account_settings_context(request):
    """ Context for the account settings page.

    Args:
        request: The request object.

    Returns:
        dict

    """
    user = request.user

    year_of_birth_options = [(unicode(year), unicode(year))
                             for year in UserProfile.VALID_YEARS]

    comuni_options = (("0", "Ninguna"), ("1", "Andalucía"), ("2", "Aragón"),
                      ("3", "Asturias"), ("4", "Baleares"), ("5", "Canarias"),
                      ("6", "Cantabria"), ("7", "Castilla y León"),
                      ("8", "Castilla - La Mancha"), ("9", "Cataluña"),
                      ("10", "Extremadura"), ("11", "Galicia"),
                      ("12", "Madrid"), ("13", "Murcia"), ("14", "Navarra"),
                      ("15", "País Vasco"), ("16", "La Rioja"),
                      ("17", "Valencia"), ("18", "Ceuta"), ("19", "Melilla"))
    esdoce_options = (("1", _("Yes")), ("2", _("No")))
    camp2_options = (("0", "--"), ("1",
                                   pgettext("Educational institution",
                                            "State")), ("2", _("Subsidized")),
                     ("3", _("Private")))

    context = {
        'auth': {},
        'duplicate_provider':
        None,
        'fields': {
            'country': {
                'options': list(countries),
            },
            'gender': {
                'options': [(choice[0], _(choice[1]))
                            for choice in UserProfile.GENDER_CHOICES],  # pylint: disable=translation-of-non-string
            },
            'language': {
                'options': released_languages(),
            },
            'level_of_education': {
                'options':
                [(choice[0], _(choice[1]))
                 for choice in UserProfile.LEVEL_OF_EDUCATION_CHOICES],  # pylint: disable=translation-of-non-string
            },
            'password': {
                'url': reverse('password_reset'),
            },
            'year_of_birth': {
                'options': year_of_birth_options,
            },
            'preferred_language': {
                'options': settings.ALL_LANGUAGES,
            },
            'comuni': {
                'options': comuni_options,
            },
            'esdoce': {
                'options': esdoce_options,
            },
            'camp2': {
                'options': camp2_options,
            }
        },
        'platform_name':
        settings.PLATFORM_NAME,
        'user_accounts_api_url':
        reverse("accounts_api", kwargs={'username': user.username}),
        'user_preferences_api_url':
        reverse('preferences_api', kwargs={'username': user.username}),
        'disable_courseware_js':
        True,
    }

    if third_party_auth.is_enabled():
        # If the account on the third party provider is already connected with another edX account,
        # we display a message to the user.
        context['duplicate_provider'] = pipeline.get_duplicate_provider(
            messages.get_messages(request))

        auth_states = pipeline.get_provider_user_states(user)

        context['auth']['providers'] = [
            {
                'id':
                state.provider.provider_id,
                'name':
                state.provider.name,  # The name of the provider e.g. Facebook
                'connected':
                state.
                has_account,  # Whether the user's edX account is connected with the provider.
                # If the user is not connected, they should be directed to this page to authenticate
                # with the particular provider, as long as the provider supports initiating a login.
                'connect_url':
                pipeline.get_login_url(
                    state.provider.provider_id,
                    pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS,
                    # The url the user should be directed to after the auth process has completed.
                    redirect_url=reverse('account_settings'),
                ),
                'accepts_logins':
                state.provider.accepts_logins,
                # If the user is connected, sending a POST request to this url removes the connection
                # information for this provider from their edX account.
                'disconnect_url':
                pipeline.get_disconnect_url(state.provider.provider_id,
                                            state.association_id),
            } for state in auth_states
        ]

    return context
Example #18
0
def account_settings_context(request):
    """ Context for the account settings page.

    Args:
        request: The request object.

    Returns:
        dict

    """
    user = request.user

    year_of_birth_options = [(unicode(year), unicode(year)) for year in UserProfile.VALID_YEARS]
    try:
        user_orders = get_user_orders(user)
    except:  # pylint: disable=bare-except
        log.exception('Error fetching order history from Otto.')
        # Return empty order list as account settings page expect a list and
        # it will be broken if exception raised
        user_orders = []

    context = {
        'auth': {},
        'duplicate_provider': None,
        'fields': {
            'country': {
                'options': list(countries),
            }, 'gender': {
                'options': [(choice[0], _(choice[1])) for choice in UserProfile.GENDER_CHOICES],  # pylint: disable=translation-of-non-string
            }, 'language': {
                'options': released_languages(),
            }, 'level_of_education': {
                'options': [(choice[0], _(choice[1])) for choice in UserProfile.LEVEL_OF_EDUCATION_CHOICES],  # pylint: disable=translation-of-non-string
            }, 'password': {
                'url': reverse('password_reset'),
            }, 'year_of_birth': {
                'options': year_of_birth_options,
            }, 'preferred_language': {
                'options': all_languages(),
            }, 'time_zone': {
                'options': UserPreference.TIME_ZONE_CHOICES,
                'enabled': settings.FEATURES.get('ENABLE_TIME_ZONE_PREFERENCE'),
            }
        },
        'platform_name': get_themed_value('PLATFORM_NAME', settings.PLATFORM_NAME),
        'user_accounts_api_url': reverse("accounts_api", kwargs={'username': user.username}),
        'user_preferences_api_url': reverse('preferences_api', kwargs={'username': user.username}),
        'disable_courseware_js': True,
        'show_program_listing': ProgramsApiConfig.current().show_program_listing,
        'order_history': user_orders
    }

    if third_party_auth.is_enabled():
        # If the account on the third party provider is already connected with another edX account,
        # we display a message to the user.
        context['duplicate_provider'] = pipeline.get_duplicate_provider(messages.get_messages(request))

        auth_states = pipeline.get_provider_user_states(user)

        context['auth']['providers'] = [{
            'id': state.provider.provider_id,
            'name': state.provider.name,  # The name of the provider e.g. Facebook
            'connected': state.has_account,  # Whether the user's edX account is connected with the provider.
            # If the user is not connected, they should be directed to this page to authenticate
            # with the particular provider, as long as the provider supports initiating a login.
            'connect_url': pipeline.get_login_url(
                state.provider.provider_id,
                pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS,
                # The url the user should be directed to after the auth process has completed.
                redirect_url=reverse('account_settings'),
            ),
            'accepts_logins': state.provider.accepts_logins,
            # If the user is connected, sending a POST request to this url removes the connection
            # information for this provider from their edX account.
            'disconnect_url': pipeline.get_disconnect_url(state.provider.provider_id, state.association_id),
        } for state in auth_states]

    return context
Example #19
0
def account_settings_context(request):
    """ Context for the account settings page.

    Args:
        request: The request object.

    Returns:
        dict

    """
    user = request.user

    year_of_birth_options = [(unicode(year), unicode(year)) for year in UserProfile.VALID_YEARS]
    try:
        user_orders = get_user_orders(user)
    except:  # pylint: disable=bare-except
        log.exception("Error fetching order history from Otto.")
        # Return empty order list as account settings page expect a list and
        # it will be broken if exception raised
        user_orders = []

    context = {
        "auth": {},
        "duplicate_provider": None,
        "fields": {
            "country": {"options": list(countries)},
            "gender": {
                "options": [
                    (choice[0], _(choice[1])) for choice in UserProfile.GENDER_CHOICES
                ]  # pylint: disable=translation-of-non-string
            },
            "language": {"options": released_languages()},
            "level_of_education": {
                "options": [
                    (choice[0], _(choice[1])) for choice in UserProfile.LEVEL_OF_EDUCATION_CHOICES
                ]  # pylint: disable=translation-of-non-string
            },
            "password": {"url": reverse("password_reset")},
            "year_of_birth": {"options": year_of_birth_options},
            "preferred_language": {"options": all_languages()},
            "time_zone": {
                "options": TIME_ZONE_CHOICES,
                "enabled": settings.FEATURES.get("ENABLE_TIME_ZONE_PREFERENCE"),
            },
        },
        "platform_name": get_themed_value("PLATFORM_NAME", settings.PLATFORM_NAME),
        "user_accounts_api_url": reverse("accounts_api", kwargs={"username": user.username}),
        "user_preferences_api_url": reverse("preferences_api", kwargs={"username": user.username}),
        "disable_courseware_js": True,
        "show_program_listing": ProgramsApiConfig.current().show_program_listing,
        "order_history": user_orders,
    }

    if third_party_auth.is_enabled():
        # If the account on the third party provider is already connected with another edX account,
        # we display a message to the user.
        context["duplicate_provider"] = pipeline.get_duplicate_provider(messages.get_messages(request))

        auth_states = pipeline.get_provider_user_states(user)

        context["auth"]["providers"] = [
            {
                "id": state.provider.provider_id,
                "name": state.provider.name,  # The name of the provider e.g. Facebook
                "connected": state.has_account,  # Whether the user's edX account is connected with the provider.
                # If the user is not connected, they should be directed to this page to authenticate
                # with the particular provider, as long as the provider supports initiating a login.
                "connect_url": pipeline.get_login_url(
                    state.provider.provider_id,
                    pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS,
                    # The url the user should be directed to after the auth process has completed.
                    redirect_url=reverse("account_settings"),
                ),
                "accepts_logins": state.provider.accepts_logins,
                # If the user is connected, sending a POST request to this url removes the connection
                # information for this provider from their edX account.
                "disconnect_url": pipeline.get_disconnect_url(state.provider.provider_id, state.association_id),
            }
            for state in auth_states
        ]

    return context