Пример #1
0
def update_preferences(username, **kwargs):
    """Update a user's preferences.

    Sets the provided preferences for the given user.

    Args:
        username (unicode): The username of the account to retrieve.

    Keyword Args:
        **kwargs (unicode): Arbitrary key-value preference pairs

    Returns:
        None

    Raises:
        ProfileUserNotFound

    """
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        raise ProfileUserNotFound
    else:
        for key, value in kwargs.iteritems():
            UserPreference.set_preference(user, key, value)
Пример #2
0
def update_preferences(username, **kwargs):
    """Update a user's preferences.

    Sets the provided preferences for the given user.

    Args:
        username (unicode): The username of the account to retrieve.

    Keyword Args:
        **kwargs (unicode): Arbitrary key-value preference pairs

    Returns:
        None

    Raises:
        ProfileUserNotFound

    """
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        raise ProfileUserNotFound
    else:
        for key, value in kwargs.iteritems():
            UserPreference.set_preference(user, key, value)
Пример #3
0
    def test_language_in_session(self):
        # language set in both the user preferences and session,
        # session should get precedence
        self.request.session['django_language'] = 'en'
        UserPreference.set_preference(self.user, LANGUAGE_KEY, 'eo')
        self.middleware.process_request(self.request)

        self.assertEquals(self.request.session['django_language'], 'en')
Пример #4
0
    def test_language_in_session(self):
        # language set in both the user preferences and session,
        # session should get precedence
        self.request.session['django_language'] = 'en'
        UserPreference.set_preference(self.user, LANGUAGE_KEY, 'eo')
        self.middleware.process_request(self.request)

        self.assertEquals(self.request.session['django_language'], 'en')
Пример #5
0
    def test_user_with_locale_claim(self):
        language = 'en'
        UserPreference.set_preference(self.user, LANGUAGE_KEY, language)
        scopes, claims = self.get_id_token_values('openid profile')

        self.assertIn('profile', scopes)

        locale = claims['locale']
        self.assertEqual(language, locale)
Пример #6
0
    def test_user_wit_locale_claim(self):
        language = 'en'
        UserPreference.set_preference(self.user, LANGUAGE_KEY, language)
        scopes, claims = self.get_new_id_token_values('openid profile')

        self.assertIn('profile', scopes)

        locale = claims['locale']
        self.assertEqual(language, locale)
Пример #7
0
def set_language(request):
    """
    This view is called when the user would like to set a language preference
    """
    user = request.user
    lang_pref = request.POST.get('language', None)

    if lang_pref:
        UserPreference.set_preference(user, LANGUAGE_KEY, lang_pref)
        return HttpResponse('{"success": true}')

    return HttpResponseBadRequest('no language provided')
 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(UserPreference.get_preference(user, LANGUAGE_KEY),
                          lang)
 def test_header_lang_pref_saved(self, lang):
     response = self.client.post(self.url,
                                 self.params,
                                 HTTP_ACCEPT_LANGUAGE=lang)
     self.assertEqual(response.status_code, 200)
     user = User.objects.get(username=self.username)
     self.assertEqual(UserPreference.get_preference(user, LANGUAGE_KEY),
                      lang)
Пример #10
0
    def test_get_set_preference(self):
        # Checks that you can set a preference and get that preference later
        # Also, tests that no preference is returned for keys that are not set

        user = UserFactory.create()
        key = 'testkey'
        value = 'testvalue'

        # does a round trip
        UserPreference.set_preference(user, key, value)
        pref = UserPreference.get_preference(user, key)

        self.assertEqual(pref, value)

        # get preference for key that doesn't exist for user
        pref = UserPreference.get_preference(user, 'testkey_none')
        self.assertIsNone(pref)
Пример #11
0
    def test_get_set_preference(self):
        # Checks that you can set a preference and get that preference later
        # Also, tests that no preference is returned for keys that are not set

        user = UserFactory.create()
        key = 'testkey'
        value = 'testvalue'

        # does a round trip
        UserPreference.set_preference(user, key, value)
        pref = UserPreference.get_preference(user, key)

        self.assertEqual(pref, value)

        # get preference for key that doesn't exist for user
        pref = UserPreference.get_preference(user, 'testkey_none')
        self.assertIsNone(pref)
Пример #12
0
    def claim_locale(self, data):
        """
        Return the locale for the users based on their preferences.
        Does not return a value if the users have not set their locale preferences.

        """

        language = UserPreference.get_preference(data['user'], LANGUAGE_KEY)
        return language
Пример #13
0
    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(UserPreference.get_preference(user, LANGUAGE_KEY))
Пример #14
0
    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(UserPreference.get_preference(user, LANGUAGE_KEY))
Пример #15
0
 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 = UserPreference.get_preference(request.user, LANGUAGE_KEY)
         if user_pref:
             request.session['django_language'] = user_pref
Пример #16
0
    def claim_locale(self, data):
        """
        Return the locale for the users based on their preferences.
        Does not return a value if the users have not set their locale preferences.

        """

        language = UserPreference.get_preference(data['user'], LANGUAGE_KEY)
        return language
Пример #17
0
    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 = UserPreference.get_preference(user, LANGUAGE_KEY)
        self.assertEqual(user_pref, lang)
Пример #18
0
    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 = UserPreference.get_preference(user, LANGUAGE_KEY)
        self.assertEqual(user_pref, lang)
Пример #19
0
def login(request):
    response = login_user(request, "")
    context = json.loads(response.content)
    if context.get("success", False):
        context.update({
            "user_name": request.user.username,
            "user_full_name": request.user.profile.name,
            "language_code": UserPreference.get_preference(request.user, LANGUAGE_KEY),
        })
        response.content = json.dumps(context, cls = DjangoJSONEncoder, indent = 2, ensure_ascii = False)   
    return response
Пример #20
0
    def claim_locale(self, data):
        """
        Return the locale for the users based on their preferences.
        Does not return a value if the users have not set their locale preferences.

        """

        language = UserPreference.get_preference(data['user'], LANGUAGE_KEY)

        # If the user has no language specified, return the default one.
        if not language:
            language = getattr(settings, 'LANGUAGE_CODE')

        return language
Пример #21
0
    def claim_locale(self, data):
        """
        Return the locale for the users based on their preferences.
        Does not return a value if the users have not set their locale preferences.

        """

        language = UserPreference.get_preference(data['user'], LANGUAGE_KEY)

        # If the user has no language specified, return the default one.
        if not language:
            language = getattr(settings, 'LANGUAGE_CODE')

        return language
Пример #22
0
 def test_language_in_user_prefs(self):
     # language set in the user preferences and not the session
     UserPreference.set_preference(self.user, LANGUAGE_KEY, 'eo')
     self.middleware.process_request(self.request)
     self.assertEquals(self.request.session['django_language'], 'eo')
Пример #23
0
 def test_header_lang_pref_saved(self, lang):
     response = self.client.post(self.url, self.params, HTTP_ACCEPT_LANGUAGE=lang)
     self.assertEqual(response.status_code, 200)
     user = User.objects.get(username=self.username)
     self.assertEqual(UserPreference.get_preference(user, LANGUAGE_KEY), lang)
Пример #24
0
def callback(request, next_page=None, required=False):
    try:
        if request.method != 'POST':
            raise PermissionDenied('0005')

        try:
            # Verifies signature and expiry time
            verified_jwt = jwt.decode(
                request.POST['assertion'],
                key=settings.AAF_SECRET,
                # audience=settings.AAF_AUDIENCE,
                # issuer=settings.AAF_ISSUER)
            )
        except jwt.ExpiredSignature:
            # Security cookie has expired
            raise PermissionDenied('0001')

        # for PyJWT > 0.4.1:
        '''
        except jwt.InvalidAudience:
            # Not for this audience
            raise PermissionDenied('0004')
            '''
        # for older PyJWT:
        if verified_jwt['aud'] != settings.AAF_AUDIENCE or verified_jwt['iss'] != settings.AAF_ISSUER:
            raise PermissionDenied('0004')

        import logging
        logging.warning(verified_jwt)

        # Verify that we haven't seen this jti value before (prevents replay
        # attacks)
        if 'jti' not in verified_jwt.keys():
            raise PermissionDenied('0002')

        jti = verified_jwt['jti']
        if JTILog.objects.filter(jti=jti).exists():
            # looks like replay
            raise PermissionDenied('0003')

        # add jti to the log
        jl = JTILog(jti=jti)
        jl.save()

        attributes = verified_jwt['https://aaf.edu.au/attributes']

        request.session['attributes'] = attributes
        request.session['jwt'] = verified_jwt
        request.session['jws'] = request.POST['assertion']

        assert 'edupersonprincipalname' in attributes.keys(), 'edupersonprincipalname not in attributes'

        # If you want to restrict access to your institution, fill in PRINCIPAL_NAME_RE and uncomment
        # The first group should be the username
        '''
        match = PRINCIPAL_NAME_RE.match(attributes['edupersonprincipalname'])
        if match is None:
            # Principal name not in expected format
            raise PermissionDenied('0006')
        username = match.groups()[0]
        '''
        username = attributes['edupersonprincipalname']  # Remove this if you have a better/shorter username you'd like to use

        email = attributes['edupersonprincipalname']

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User.objects.create_user(
                username=username,
                email=email,
                password=None)  # non-usable password
            user.save()

            UserPreference.set_preference(user, LANGUAGE_KEY, get_language())

        # blech - we're caching the user's name both in the Django User object
        # and the edX UserProfile object, and we don't really want either.

        # cache some attributes
        # Django shouldn't touch the database if they haven't changed, so no perf issue
        if 'givenname' in attributes.keys():
            user.first_name = attributes['givenname']

        if 'surname' in attributes.keys():
            user.last_name = attributes['surname']

        # This should only be done at user creation time. We do it here
        # because we have some old entries in the database that we'd like to
        # clean up automatically.
        if 'edupersonprincipalname' in attributes.keys():
            user.email = attributes['edupersonprincipalname']

        user.save()

        # Look up the UserProfile and update it
        try:
            profile = UserProfile.objects.get(user=user)
        except UserProfile.DoesNotExist:
            # create a new one
            profile = UserProfile(user=user)
            profile.save()

        # update the profile's name
        profile.update_name('%s %s' % (user.first_name, user.last_name))

        create_comments_service_user(user)

        # Temporary workaround: http://stackoverflow.com/a/23771930
        user.backend = 'django.contrib.auth.backends.ModelBackend'

        djauth.login(request, user)

        # done!
        if next_page:
            return redirect(next_page)
        else:
            # If we're in lms, we want to go to dashboard. For cms, go to homepage.
            print 'doing the fallback thing'
            try:
                return redirect('dashboard')
            except NoReverseMatch:
                return redirect('homepage')

    except PermissionDenied as e:
        if 'attributes' in request.session.keys():
            del request.session['attributes']
        djauth.logout(request)

        # messages.add_message(request, messages.ERROR, 'Could not log you in (error %s). Please try again.' % e.message)

        # bounce back to login page
        # TODO you could bounce to a message page if the messages thing above doesn't integrate nicely
        return redirect('dashboard')  # TODO: probably better to send directly to index, but I can't find it
Пример #25
0
 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(UserPreference.get_preference(user, LANGUAGE_KEY), lang)
Пример #26
0
 def test_language_in_user_prefs(self):
     # language set in the user preferences and not the session
     UserPreference.set_preference(self.user, LANGUAGE_KEY, 'eo')
     self.middleware.process_request(self.request)
     self.assertEquals(self.request.session['django_language'], 'eo')