Пример #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')
Пример #8
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)
Пример #9
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)
Пример #10
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')
Пример #11
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
Пример #12
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')