Exemplo n.º 1
0
    def test_login_teams_automapping(self):
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING = {'teamname': 'groupname',
                                                   'otherteam': 'othergroup'}
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING_AUTO = True
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING_AUTO_BLACKLIST = ['django-group1', 'django-group2']
        user = User.objects.create_user('testuser', '*****@*****.**')
        group1 = Group(name='django-group1')
        group1.save()
        group2 = Group(name='django-group2')
        group2.save()
        group3 = Group(name='django-group3')
        group3.save()
        user.save()
        useropenid = UserOpenID(
            user=user,
            claimed_id='http://example.com/identity',
            display_id='http://example.com/identity')
        useropenid.save()

        # Posting in an identity URL begins the authentication request:
        response = self.client.post('/openid/login/',
            {'openid_identifier': 'http://example.com/identity',
             'next': '/getuser/'})
        self.assertContains(response, 'OpenID transaction in progress')

        # Complete the request
        openid_request = self.provider.parseFormPost(response.content)
        openid_response = openid_request.answer(True)
        teams_request = teams.TeamsRequest.fromOpenIDRequest(openid_request)
        
        self.assertEqual(group1 in user.groups.all(), False)
        self.assertEqual(group2 in user.groups.all(), False)
        self.assertTrue(group3 not in user.groups.all())
Exemplo n.º 2
0
def profile_edit_openids_complete(request):
    openid_response = openid_views.parse_openid_response(request)
    yours_msg = _('The identity %s has already been claimed by you.')
    theirs_msg = _('The identity %s has already been claimed by another user.')
    if openid_response:
        if openid_response.status == openid_views.SUCCESS:
            url = openid_response.identity_url
            try:
                user_openid = UserOpenID.objects.get(
                    claimed_id__exact=url)
            except UserOpenID.DoesNotExist:
                user_openid = UserOpenID(user=request.user,
                claimed_id=openid_response.identity_url,
                display_id=openid_response.endpoint.getDisplayIdentifier())
                user_openid.save()
                messages.info(request,
                    _('The identity %s has been saved.') % url)
            else:
                if user_openid.user == request.user:
                    messages.error(request, yours_msg % url)
                else:
                    messages.error(request, theirs_msg % url)
        elif openid_response.status == openid_views.FAILURE:
            messages.error(request, _('OpenID authentication failed: %s') %
                openid_response.message)
        elif openid_response.status == openid_views.CANCEL:
            return messages.error(request, _('Authentication cancelled.'))
        else:
            return messages.error(
                _('Unknown OpenID response type: %r') % openid_response.status)
    else:
        return messages.error(_('This is an OpenID relying party endpoint.'))
    return http.HttpResponseRedirect(reverse('users_profile_edit_openids'))
    def test_login_complete_signals_login(self):
        # An oauth_login_complete signal is emitted including the
        # request and sreg_response.
        user = User.objects.create_user('someuser', '*****@*****.**')
        useropenid = UserOpenID(
            user=user,
            claimed_id='http://example.com/identity',
            display_id='http://example.com/identity')
        useropenid.save()
        response = self.client.post('/openid/login/',
            {'openid_identifier': 'http://example.com/identity'})
        openid_request = self.provider.parseFormPost(response.content)
        openid_response = openid_request.answer(True)
        # Use a closure to test whether the signal handler was called.
        self.signal_handler_called = False
        def login_callback(sender, **kwargs):
            self.assertTrue(isinstance(
                kwargs.get('request', None), HttpRequest))
            self.assertTrue(isinstance(
                kwargs.get('openid_response', None), SuccessResponse))
            self.signal_handler_called = True
        openid_login_complete.connect(login_callback)

        response = self.complete(openid_response)

        self.assertTrue(self.signal_handler_called)
        openid_login_complete.disconnect(login_callback)
Exemplo n.º 4
0
def profile_edit_openids_complete(request):
    openid_response = openid_views.parse_openid_response(request)
    yours_msg = _('The identity %s has already been claimed by you.')
    theirs_msg = _('The identity %s has already been claimed by another user.')
    if openid_response:
        if openid_response.status == openid_views.SUCCESS:
            url = openid_response.identity_url
            try:
                user_openid = UserOpenID.objects.get(
                    claimed_id__exact=url)
            except UserOpenID.DoesNotExist:
                user_openid = UserOpenID(user=request.user,
                claimed_id=openid_response.identity_url,
                display_id=openid_response.endpoint.getDisplayIdentifier())
                user_openid.save()
                messages.info(request,
                    _('The identity %s has been saved.') % url)
            else:
                if user_openid.user == request.user:
                    messages.error(request, yours_msg % url)
                else:
                    messages.error(request, theirs_msg % url)
        elif openid_response.status == openid_views.FAILURE:
            messages.error(request, _('OpenID authentication failed: %s') %
                openid_response.message)
        elif openid_response.status == openid_views.CANCEL:
            return messages.error(request, _('Authentication cancelled.'))
        else:
            return messages.error(
                _('Unknown OpenID response type: %r') % openid_response.status)
    else:
        return messages.error(_('This is an OpenID relying party endpoint.'))
    return http.HttpResponseRedirect(reverse('users_profile_edit_openids'))
Exemplo n.º 5
0
    def test_login_sso(self):
        settings.OPENID_SSO_SERVER_URL = 'http://example.com/identity'
        user = User.objects.create_user('someuser', '*****@*****.**')
        useropenid = UserOpenID(
            user=user,
            claimed_id='http://example.com/identity',
            display_id='http://example.com/identity')
        useropenid.save()

        # Requesting the login form immediately begins an
        # authentication request.
        response = self.client.get('/openid/login/', {'next': '/getuser/'})
        self.assertEquals(response.status_code, 200)
        self.assertContains(response, 'OpenID transaction in progress')

        openid_request = self.provider.parseFormPost(response.content)
        self.assertEquals(openid_request.mode, 'checkid_setup')
        self.assertTrue(openid_request.return_to.startswith(
                'http://testserver/openid/complete/'))

        # Complete the request.  The user is redirected to the next URL.
        openid_response = openid_request.answer(True)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in:
        response = self.client.get('/getuser/')
        self.assertEquals(response.content, 'someuser')
Exemplo n.º 6
0
    def test_login_teams_automapping(self):
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING = {'teamname': 'groupname',
                                                   'otherteam': 'othergroup'}
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING_AUTO = True
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING_AUTO_BLACKLIST = ['django-group1', 'django-group2']
        user = User.objects.create_user('testuser', '*****@*****.**')
        group1 = Group(name='django-group1')
        group1.save()
        group2 = Group(name='django-group2')
        group2.save()
        group3 = Group(name='django-group3')
        group3.save()
        user.save()
        useropenid = UserOpenID(
            user=user,
            claimed_id='http://example.com/identity',
            display_id='http://example.com/identity')
        useropenid.save()

        # Posting in an identity URL begins the authentication request:
        response = self.client.post('/openid/login/',
            {'openid_identifier': 'http://example.com/identity',
             'next': '/getuser/'})
        self.assertContains(response, 'OpenID transaction in progress')

        # Complete the request
        openid_request = self.provider.parseFormPost(response.content)
        openid_response = openid_request.answer(True)
        teams_request = teams.TeamsRequest.fromOpenIDRequest(openid_request)
        
        self.assertEqual(group1 in user.groups.all(), False)
        self.assertEqual(group2 in user.groups.all(), False)
        self.assertTrue(group3 not in user.groups.all())
Exemplo n.º 7
0
    def test_login(self):
        user = User.objects.create_user('someuser', '*****@*****.**')
        useropenid = UserOpenID(
            user=user,
            claimed_id='http://example.com/identity',
            display_id='http://example.com/identity')
        useropenid.save()

        # The login form is displayed:
        response = self.client.get('/openid/login/')
        self.assertTemplateUsed(response, 'openid/login.html')

        # Posting in an identity URL begins the authentication request:
        response = self.client.post('/openid/login/',
            {'openid_identifier': 'http://example.com/identity',
             'next': '/getuser/'})
        self.assertContains(response, 'OpenID transaction in progress')

        openid_request = self.provider.parseFormPost(response.content)
        self.assertEquals(openid_request.mode, 'checkid_setup')
        self.assertTrue(openid_request.return_to.startswith(
                'http://testserver/openid/complete/'))

        # Complete the request.  The user is redirected to the next URL.
        openid_response = openid_request.answer(True)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in:
        response = self.client.get('/getuser/')
        self.assertEquals(response.content, 'someuser')
Exemplo n.º 8
0
    def test_login_sso(self):
        settings.OPENID_SSO_SERVER_URL = 'http://example.com/identity'
        user = User.objects.create_user('someuser', '*****@*****.**')
        useropenid = UserOpenID(user=user,
                                claimed_id='http://example.com/identity',
                                display_id='http://example.com/identity')
        useropenid.save()

        # Requesting the login form immediately begins an
        # authentication request.
        response = self.client.get('/openid/login/', {'next': '/getuser/'})
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'OpenID transaction in progress')

        openid_request = self.provider.parseFormPost(response.content)
        self.assertEqual(openid_request.mode, 'checkid_setup')
        self.assertTrue(
            openid_request.return_to.startswith(
                'http://testserver/openid/complete/'))

        # Complete the request.  The user is redirected to the next URL.
        openid_response = openid_request.answer(True)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in:
        response = self.client.get('/getuser/')
        self.assertEqual(response.content, 'someuser')
Exemplo n.º 9
0
    def test_login_no_next(self):
        """Logins with no next parameter redirect to LOGIN_REDIRECT_URL."""
        user = User.objects.create_user('someuser', '*****@*****.**')
        useropenid = UserOpenID(user=user,
                                claimed_id='http://example.com/identity',
                                display_id='http://example.com/identity')
        useropenid.save()

        settings.LOGIN_REDIRECT_URL = '/getuser/'
        response = self.client.post(
            '/openid/login/',
            {'openid_identifier': 'http://example.com/identity'})
        self.assertContains(response, 'OpenID transaction in progress')

        openid_request = self.provider.parseFormPost(response.content)
        self.assertEqual(openid_request.mode, 'checkid_setup')
        self.assertTrue(
            openid_request.return_to.startswith(
                'http://testserver/openid/complete/'))

        # Complete the request.  The user is redirected to the next URL.
        openid_response = openid_request.answer(True)
        response = self.complete(openid_response)
        self.assertRedirects(response,
                             'http://testserver' + settings.LOGIN_REDIRECT_URL)
Exemplo n.º 10
0
    def test_login(self):
        user = User.objects.create_user('someuser', '*****@*****.**')
        useropenid = UserOpenID(user=user,
                                claimed_id='http://example.com/identity',
                                display_id='http://example.com/identity')
        useropenid.save()

        # The login form is displayed:
        response = self.client.get('/openid/login/')
        self.assertTemplateUsed(response, 'openid/login.html')

        # Posting in an identity URL begins the authentication request:
        response = self.client.post(
            '/openid/login/', {
                'openid_identifier': 'http://example.com/identity',
                'next': '/getuser/'
            })
        self.assertContains(response, 'OpenID transaction in progress')

        openid_request = self.provider.parseFormPost(response.content)
        self.assertEqual(openid_request.mode, 'checkid_setup')
        self.assertTrue(
            openid_request.return_to.startswith(
                'http://testserver/openid/complete/'))

        # Complete the request.  The user is redirected to the next URL.
        openid_response = openid_request.answer(True)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in:
        response = self.client.get('/getuser/')
        self.assertEqual(response.content, 'someuser')
Exemplo n.º 11
0
 def create_user(self):
     user = User(username=self._username)
     user.save()
     # Associate our newly created user with the identity URL.
     useropenid = UserOpenID(
         user=user, claimed_id=self._identity_url,
         display_id=self._identity_url)
     useropenid.save()
Exemplo n.º 12
0
 def create_user(self):
     user = User(username=self._username)
     user.save()
     # Associate our newly created user with the identity URL.
     useropenid = UserOpenID(user=user,
                             claimed_id=self._identity_url,
                             display_id=self._identity_url)
     useropenid.save()
Exemplo n.º 13
0
    def associate_openid(self, user, openid_response):
        """Associate an OpenID with a user account."""
        # Check to see if this OpenID has already been claimed.
        try:
            user_openid = UserOpenID.objects.get(
                claimed_id__exact=openid_response.identity_url)
        except UserOpenID.DoesNotExist:
            
            # find other users with the same email, only allow a single merge per user
            others = User.objects.filter(email=user.email, profile__openid_merge=False)
            
            # will only trust certain OpenID providers to do the right thing
            url = urlparse(openid_response.identity_url)
            
            # let us know if you need more providers
            trusted = False
            for provider in ( 'www.google.com',  'me.yahoo.com', 'myopenid.com',
                            'livejournal.com', 'blogspot.com', 'openid.aol.com',
                            'wordpress.com'):
                trusted = trusted or url.netloc.endswith(provider)
            
            # you can override migration from the settings
            trusted = trusted and settings.ALLOW_MIGRATION                       
            
            # this merges the authenticated user with an existing user
            if others and trusted:
                print '*** merging an existing user into this openid'
                print '*** openid url %s' % openid_response.identity_url
                # delete the old user
                user.delete()
                
                #  replace with the new user and update the profile accordingly
                user = others[0]
                user.save()
                
                # update the profile with the new information
                user.profile.openid_merge = True
                user.profile.just_merged  = True
                user.profile.openid = openid_response.identity_url
                user.profile.save()                

            user_openid = UserOpenID(
                user=user,
                claimed_id=openid_response.identity_url,
                display_id=openid_response.endpoint.getDisplayIdentifier())
            user_openid.save()
        else:
            if user_openid.user != user:
                raise IdentityAlreadyClaimed(
                    "The identity %s has already been claimed"
                    % openid_response.identity_url)

        return user
Exemplo n.º 14
0
Arquivo: auth.py Projeto: gcr/twg
    def associate_openid(self, user, openid_response):
        """Associate an OpenID with a user account."""
        # Check to see if this OpenID has already been claimed.
        try:
            user_openid = UserOpenID.objects.get(claimed_id__exact=openid_response.identity_url)
        except UserOpenID.DoesNotExist:
            user_openid = UserOpenID(
                user=user,
                claimed_id=openid_response.identity_url,
                display_id=openid_response.endpoint.getDisplayIdentifier(),
            )
            user_openid.save()
        else:
            if user_openid.user != user:
                raise IdentityAlreadyClaimed("The identity %s has already been claimed" % openid_response.identity_url)

        return user_openid
Exemplo n.º 15
0
    def execute(self, args):
        self._prepare(args)

        from django.contrib.auth.models import User
        from django_openid_auth.models import UserOpenID

        # Django took over logging and we need it back
        self.reset_logger(args, True)

        try:
            user = User.objects.get(username=args.username)
        except User.DoesNotExist:

            # We can only give up at that point, the user must exist.
            self.logger.error('Error: No such user [{}]'.format(args.username))
            sys.exit(self.SYS_ERROR.NO_SUCH_WEB_ADMIN_USER)

        claimed_id = getattr(args, 'claimed-id')

        try:
            user_open_id = UserOpenID.objects.get(user=user)
        except UserOpenID.DoesNotExist:
            user_open_id = UserOpenID()
            user_open_id.user = user

        user_open_id.claimed_id = claimed_id
        user_open_id.display_id = claimed_id  # Same value for display_id
        user_open_id.save()

        self._ok(args)
Exemplo n.º 16
0
def confirm_openid(request, openid_id):

    session = {'id': request.session.session_key}
    current_url = settings.SITE_URL + request.path

    oidutil.log = openid_logging
    openid_consumer = consumer.Consumer(session, DjangoOpenIDStore())

    if request.method == 'POST':
        info = openid_consumer.complete(request.POST, current_url)
    else:
        info = openid_consumer.complete(request.GET, current_url)

    if info.status == consumer.FAILURE:
        return render_to_response('account/openid_confirmationfailed.html',
                                  {'message': info.message},
                                  context_instance=RequestContext(request))
    elif info.status == consumer.CANCEL:
        return render_to_response('account/openid_confirmationfailed.html',
                                  {'message': '(cancelled by user)'},
                                  context_instance=RequestContext(request))
    elif info.status != consumer.SUCCESS:
        return render_to_response('account/openid_confirmationfailed.html',
                                  {'message': '(unknown verification error)'},
                                  context_instance=RequestContext(request))

    try:
        unconfirmed = UnconfirmedOpenId.objects.get(id=openid_id,
                                                    user=request.user)
    except UnconfirmedOpenId.DoesNotExist:
        return render_to_response(
            'account/openid_confirmationfailed.html',
            {'message': 'ID %s not found in the database.' % openid_id},
            context_instance=RequestContext(request))

    # TODO: check for a reasonable expiration time
    confirmed = ConfirmedOpenId()
    confirmed.user = unconfirmed.user
    confirmed.ip_address = request.META['REMOTE_ADDR']
    confirmed.openid = unconfirmed.openid
    confirmed.save()

    unconfirmed.delete()

    # if there's a single image in this user's profile, assign it to the new email
    photos = confirmed.user.photos
    if photos.count() == 1:
        confirmed.set_photo(photos.get())

    # Also allow user to login using this OpenID (if not taken already)
    if not UserOpenID.objects.filter(claimed_id=confirmed.openid).exists():
        user_openid = UserOpenID()
        user_openid.user = request.user
        user_openid.claimed_id = confirmed.openid
        user_openid.display_id = confirmed.openid
        user_openid.save()

    return HttpResponseRedirect(reverse('libravatar.account.views.profile'))
Exemplo n.º 17
0
    def test_login_teams(self):
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING = {
            'teamname': 'groupname',
            'otherteam': 'othergroup'
        }
        user = User.objects.create_user('testuser', '*****@*****.**')
        group = Group(name='groupname')
        group.save()
        ogroup = Group(name='othergroup')
        ogroup.save()
        user.groups.add(ogroup)
        user.save()
        useropenid = UserOpenID(user=user,
                                claimed_id='http://example.com/identity',
                                display_id='http://example.com/identity')
        useropenid.save()

        # Posting in an identity URL begins the authentication request:
        response = self.client.post(
            '/openid/login/', {
                'openid_identifier': 'http://example.com/identity',
                'next': '/getuser/'
            })
        self.assertContains(response, 'OpenID transaction in progress')

        # Complete the request
        openid_request = self.provider.parseFormPost(response.content)
        openid_response = openid_request.answer(True)
        teams_request = teams.TeamsRequest.fromOpenIDRequest(openid_request)
        teams_response = teams.TeamsResponse.extractResponse(
            teams_request, 'teamname,some-other-team')
        openid_response.addExtension(teams_response)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in as testuser
        response = self.client.get('/getuser/')
        self.assertEqual(response.content, 'testuser')

        # The user's groups have been updated.
        user = User.objects.get(username='******')
        self.assertTrue(group in user.groups.all())
        self.assertTrue(ogroup not in user.groups.all())
Exemplo n.º 18
0
    def test_login_uses_sreg_extra_fields(self):
        # The configurable sreg attributes are used in the request.
        settings.OPENID_SREG_EXTRA_FIELDS = ('language',)
        user = User.objects.create_user('testuser', '*****@*****.**')
        useropenid = UserOpenID(
            user=user,
            claimed_id='http://example.com/identity',
            display_id='http://example.com/identity')
        useropenid.save()

        # Posting in an identity URL begins the authentication request:
        response = self.client.post('/openid/login/',
            {'openid_identifier': 'http://example.com/identity',
             'next': '/getuser/'})

        openid_request = self.provider.parseFormPost(response.content)
        sreg_request = sreg.SRegRequest.fromOpenIDRequest(openid_request)
        for field in ('email', 'fullname', 'nickname', 'language'):
            self.assertTrue(field in sreg_request)
Exemplo n.º 19
0
    def associate_openid(self, user, openid_response):
        """Associate an OpenID with a user account."""
        # Check to see if this OpenID has already been claimed.
        try:
            user_openid = UserOpenID.objects.get(
                claimed_id__exact=openid_response.identity_url)
        except UserOpenID.DoesNotExist:
            user_openid = UserOpenID(
                user=user,
                claimed_id=openid_response.identity_url,
                display_id=openid_response.endpoint.getDisplayIdentifier())
            user_openid.save()
        else:
            if user_openid.user != user:
                raise IdentityAlreadyClaimed(
                    "The identity %s has already been claimed" %
                    openid_response.identity_url)

        return user_openid
Exemplo n.º 20
0
    def get_openid_authed_user_with_teams(self, user, teams_str):
        useropenid = UserOpenID(
            user=user,
            claimed_id='http://example.com/identity',
            display_id='http://example.com/identity')
        useropenid.save()

        # Posting in an identity URL begins the authentication request:
        response = self.client.post('/openid/login/',
            {'openid_identifier': 'http://example.com/identity'})

        # Complete the request
        openid_request = self.provider.parseFormPost(response.content)
        openid_response = openid_request.answer(True)
        teams_request = teams.TeamsRequest.fromOpenIDRequest(openid_request)
        teams_response = teams.TeamsResponse.extractResponse(
            teams_request, teams_str)
        openid_response.addExtension(teams_response)
        response = self.complete(openid_response)
        return User.objects.get(username=user.username)
Exemplo n.º 21
0
    def test_login_update_details(self):
        settings.OPENID_UPDATE_DETAILS_FROM_SREG = True
        user = User.objects.create_user('testuser', '*****@*****.**')
        useropenid = UserOpenID(user=user,
                                claimed_id='http://example.com/identity',
                                display_id='http://example.com/identity')
        useropenid.save()

        # Posting in an identity URL begins the authentication request:
        response = self.client.post(
            '/openid/login/', {
                'openid_identifier': 'http://example.com/identity',
                'next': '/getuser/'
            })
        self.assertContains(response, 'OpenID transaction in progress')

        # Complete the request, passing back some simple registration
        # data.  The user is redirected to the next URL.
        openid_request = self.provider.parseFormPost(response.content)
        sreg_request = sreg.SRegRequest.fromOpenIDRequest(openid_request)
        openid_response = openid_request.answer(True)
        sreg_response = sreg.SRegResponse.extractResponse(
            sreg_request, {
                'nickname': 'someuser',
                'fullname': 'Some User',
                'email': '*****@*****.**'
            })
        openid_response.addExtension(sreg_response)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in as testuser (the passed in
        # nickname has not caused the username to change).
        response = self.client.get('/getuser/')
        self.assertEqual(response.content, 'testuser')

        # The user's full name and email have been updated.
        user = User.objects.get(username='******')
        self.assertEqual(user.first_name, 'Some')
        self.assertEqual(user.last_name, 'User')
        self.assertEqual(user.email, '*****@*****.**')
Exemplo n.º 22
0
    def execute(self, args):
        self._prepare(args)

        from django.contrib.auth.models import User
        from django_openid_auth.models import UserOpenID

        # Django took over logging and we need it back
        self.reset_logger(args, True)

        try:
            user = User.objects.get(username=args.username)
        except User.DoesNotExist:

            # We can only give up at that point, the user must exist.
            self.logger.error('Error: No such user [{}]'.format(args.username))
            sys.exit(self.SYS_ERROR.NO_SUCH_WEB_ADMIN_USER)

        claimed_id = getattr(args, 'claimed-id')

        try:
            user_open_id = UserOpenID.objects.get(user=user)
        except UserOpenID.DoesNotExist:
            user_open_id = UserOpenID()
            user_open_id.user = user

        user_open_id.claimed_id = claimed_id
        user_open_id.display_id = claimed_id # Same value for display_id
        user_open_id.save()

        self._ok(args)
Exemplo n.º 23
0
    def test_login_teams(self):
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING = {'teamname': 'groupname',
                                                   'otherteam': 'othergroup'}
        user = User.objects.create_user('testuser', '*****@*****.**')
        group = Group(name='groupname')
        group.save()
        ogroup = Group(name='othergroup')
        ogroup.save()
        user.groups.add(ogroup)
        user.save()
        useropenid = UserOpenID(
            user=user,
            claimed_id='http://example.com/identity',
            display_id='http://example.com/identity')
        useropenid.save()

        # Posting in an identity URL begins the authentication request:
        response = self.client.post('/openid/login/',
            {'openid_identifier': 'http://example.com/identity',
             'next': '/getuser/'})
        self.assertContains(response, 'OpenID transaction in progress')

        # Complete the request
        openid_request = self.provider.parseFormPost(response.content)
        openid_response = openid_request.answer(True)
        teams_request = teams.TeamsRequest.fromOpenIDRequest(openid_request)
        teams_response = teams.TeamsResponse.extractResponse(
            teams_request, 'teamname,some-other-team')
        openid_response.addExtension(teams_response)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in as testuser
        response = self.client.get('/getuser/')
        self.assertEquals(response.content, 'testuser')

        # The user's groups have been updated.
        user = User.objects.get(username='******')
        self.assertTrue(group in user.groups.all())
        self.assertTrue(ogroup not in user.groups.all())
Exemplo n.º 24
0
    def test_login_update_details(self):
        settings.OPENID_UPDATE_DETAILS_FROM_SREG = True
        user = User.objects.create_user('testuser', '*****@*****.**')
        useropenid = UserOpenID(
            user=user,
            claimed_id='http://example.com/identity',
            display_id='http://example.com/identity')
        useropenid.save()

        # Posting in an identity URL begins the authentication request:
        response = self.client.post('/openid/login/',
            {'openid_identifier': 'http://example.com/identity',
             'next': '/getuser/'})
        self.assertContains(response, 'OpenID transaction in progress')

        # Complete the request, passing back some simple registration
        # data.  The user is redirected to the next URL.
        openid_request = self.provider.parseFormPost(response.content)
        sreg_request = sreg.SRegRequest.fromOpenIDRequest(openid_request)
        openid_response = openid_request.answer(True)
        sreg_response = sreg.SRegResponse.extractResponse(
            sreg_request, {'nickname': 'someuser', 'fullname': 'Some User',
                           'email': '*****@*****.**'})
        openid_response.addExtension(sreg_response)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in as testuser (the passed in
        # nickname has not caused the username to change).
        response = self.client.get('/getuser/')
        self.assertEquals(response.content, 'testuser')

        # The user's full name and email have been updated.
        user = User.objects.get(username='******')
        self.assertEquals(user.first_name, 'Some')
        self.assertEquals(user.last_name, 'User')
        self.assertEquals(user.email, '*****@*****.**')
Exemplo n.º 25
0
    def do_request(self, data, *args, **kwargs):  # pylint: disable=unused-argument
        '''
        Handle request, called by get() or post()
        '''
        session = {'id': self.request.session.session_key}
        current_url = self.request.build_absolute_uri('/')[:-1] + \
            self.request.path
        openid_consumer = consumer.Consumer(session, DjangoOpenIDStore())
        info = openid_consumer.complete(data, current_url)
        if info.status == consumer.FAILURE:
            messages.error(
                self.request,
                _('Confirmation failed: "') + str(info.message) + '"')
            return HttpResponseRedirect(reverse_lazy('profile'))

        if info.status == consumer.CANCEL:
            messages.error(self.request, _('Cancelled by user'))
            return HttpResponseRedirect(reverse_lazy('profile'))

        if info.status != consumer.SUCCESS:
            messages.error(self.request, _('Unknown verification error'))
            return HttpResponseRedirect(reverse_lazy('profile'))

        try:
            unconfirmed = self.model.objects.get(  # pylint: disable=no-member
                user=self.request.user, id=kwargs['openid_id'])
        except self.model.DoesNotExist:  # pylint: disable=no-member
            messages.error(self.request, _('ID does not exist'))
            return HttpResponseRedirect(reverse_lazy('profile'))

        # TODO: Check for a reasonable expiration time
        confirmed = self.model_confirmed()
        confirmed.user = unconfirmed.user
        confirmed.ip_address = get_client_ip(self.request)[0]
        confirmed.openid = unconfirmed.openid
        confirmed.save()

        unconfirmed.delete()

        # If there is a single image in this user's profile
        # assign it to the new id
        if self.request.user.photo_set.count() == 1:
            confirmed.set_photo(self.request.user.photo_set.first())

        # Also allow user to login using this OpenID (if not already taken)
        if not UserOpenID.objects.filter(claimed_id=confirmed.openid).exists():  # pylint: disable=no-member
            user_openid = UserOpenID()
            user_openid.user = self.request.user
            user_openid.claimed_id = confirmed.openid
            user_openid.display_id = confirmed.openid
            user_openid.save()
        return HttpResponseRedirect(reverse_lazy('profile'))
Exemplo n.º 26
0
    def test_login_no_next(self):
        """Logins with no next parameter redirect to LOGIN_REDIRECT_URL."""
        user = User.objects.create_user('someuser', '*****@*****.**')
        useropenid = UserOpenID(
            user=user,
            claimed_id='http://example.com/identity',
            display_id='http://example.com/identity')
        useropenid.save()

        settings.LOGIN_REDIRECT_URL = '/getuser/'
        response = self.client.post('/openid/login/',
            {'openid_identifier': 'http://example.com/identity'})
        self.assertContains(response, 'OpenID transaction in progress')

        openid_request = self.provider.parseFormPost(response.content)
        self.assertEquals(openid_request.mode, 'checkid_setup')
        self.assertTrue(openid_request.return_to.startswith(
                'http://testserver/openid/complete/'))

        # Complete the request.  The user is redirected to the next URL.
        openid_response = openid_request.answer(True)
        response = self.complete(openid_response)
        self.assertRedirects(
            response, 'http://testserver' + settings.LOGIN_REDIRECT_URL)
Exemplo n.º 27
0
def confirm_openid(request, openid_id):

    session = {'id': request.session.session_key}
    current_url = settings.SITE_URL + request.path

    oidutil.log = openid_logging
    openid_consumer = consumer.Consumer(session, DjangoOpenIDStore())

    if request.method == 'POST':
        info = openid_consumer.complete(request.POST, current_url)
    else:
        info = openid_consumer.complete(request.GET, current_url)

    if info.status == consumer.FAILURE:
        return render_to_response('account/openid_confirmationfailed.html', {'message': info.message},
                                  context_instance=RequestContext(request))
    elif info.status == consumer.CANCEL:
        return render_to_response('account/openid_confirmationfailed.html', {'message': '(cancelled by user)'},
                                  context_instance=RequestContext(request))
    elif info.status != consumer.SUCCESS:
        return render_to_response('account/openid_confirmationfailed.html', {'message': '(unknown verification error)'},
                                  context_instance=RequestContext(request))

    try:
        unconfirmed = UnconfirmedOpenId.objects.get(id=openid_id, user=request.user)
    except UnconfirmedOpenId.DoesNotExist:
        return render_to_response('account/openid_confirmationfailed.html',
                                  {'message': 'ID %s not found in the database.' % openid_id},
                                  context_instance=RequestContext(request))

    # TODO: check for a reasonable expiration time
    confirmed = ConfirmedOpenId()
    confirmed.user = unconfirmed.user
    confirmed.ip_address = '0.0.0.0'
    confirmed.openid = unconfirmed.openid
    confirmed.save()

    unconfirmed.delete()

    # if there's a single image in this user's profile, assign it to the new email
    photos = confirmed.user.photos
    if photos.count() == 1:
        confirmed.set_photo(photos.get())

    # Also allow user to login using this OpenID (if not taken already)
    if not UserOpenID.objects.filter(claimed_id=confirmed.openid).exists():
        user_openid = UserOpenID()
        user_openid.user = request.user
        user_openid.claimed_id = confirmed.openid
        user_openid.display_id = confirmed.openid
        user_openid.save()

    return HttpResponseRedirect(reverse('libravatar.account.views.profile'))
Exemplo n.º 28
0
def login(request):
    data = {}
    data['response'] = request.GET["openid.claimed_id"]
    data['id'] = request.GET["openid.claimed_id"][36:]
    data['url'] = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key="+settings.STEAM_API_KEY+"&steamids="+data['id']

    claim = data['response']

    # Get public info
    data['info'] = json.loads(urllib.urlopen(data["url"]).read())["response"]["players"][0]

    handle = data['info']['personaname']
    steamid = data['info']['steamid']
    url = data['info']['profileurl']
    avatar = data['info']['avatar']
    avatarM = data['info']['avatarmedium']
    avatarL = data['info']['avatarfull']
    try:
        primarygroup = data['info']['primaryclanid']
    except KeyError:
        primarygroup = ""
    try:
        realname = data['info']['realname']
    except KeyError:
        realname = ""

    # Find the user
    try:
        useroid = UserOpenID.objects.get(claimed_id=claim)

        # Get them by steamid, then get the User instance associated with this
        # profile.
        userP = UserProfile.objects.get(steamid=steamid)
        user = User.objects.get(id=userP.user_id)

    # New user
    except UserOpenID.DoesNotExist:
        # Slugify their current display name, this will be used for internal control panels only.
        slugName = "{0}-{1}".format(slugify(handle), steamid[len(steamid)-3:len(steamid)])
        user = User.objects.create_user(username=slugName, email='', password='******')
        user.save()
        useroid = UserOpenID(user=user, claimed_id=claim, display_id=claim)
        useroid.save()
    try:
        up = UserProfile.objects.get(user_id=user.id)
    except UserProfile.DoesNotExist:
        up = UserProfile(user_id=user.id)
        up.save()

    # User exists, fill out profile, which is auto-filled with blanks atm.
    up.handle=handle
    up.steamid=steamid
    up.url=url
    up.avatar=avatar
    up.avatarM=avatarM
    up.avatarL=avatarL
    up.primarygroup=primarygroup
    up.realname=realname

    up.save()

    # Stole these lines from inside the openid_auth files. idk why now
    # PROB. IMPORTANT THO
    openid_response = parse_openid_response(request)
    user = authenticate(openid_response=openid_response)

    auth_login(request, user)

    return HttpResponseRedirect('/')
Exemplo n.º 29
0
    def test_login_attribute_exchange(self):
        settings.OPENID_UPDATE_DETAILS_FROM_SREG = True
        user = User.objects.create_user('testuser', '*****@*****.**')
        useropenid = UserOpenID(user=user,
                                claimed_id='http://example.com/identity',
                                display_id='http://example.com/identity')
        useropenid.save()

        # Configure the provider to advertise attribute exchange
        # protocol and start the authentication process:
        self.provider.type_uris.append('http://openid.net/srv/ax/1.0')
        response = self.client.post(
            '/openid/login/', {
                'openid_identifier': 'http://example.com/identity',
                'next': '/getuser/'
            })
        self.assertContains(response, 'OpenID transaction in progress')

        # The resulting OpenID request uses the Attribute Exchange
        # extension rather than the Simple Registration extension.
        openid_request = self.provider.parseFormPost(response.content)
        sreg_request = sreg.SRegRequest.fromOpenIDRequest(openid_request)
        self.assertEqual(sreg_request.required, [])
        self.assertEqual(sreg_request.optional, [])

        fetch_request = ax.FetchRequest.fromOpenIDRequest(openid_request)
        self.assertTrue('http://axschema.org/contact/email' in fetch_request)
        self.assertTrue('http://axschema.org/namePerson' in fetch_request)
        self.assertTrue(
            'http://axschema.org/namePerson/first' in fetch_request)
        self.assertTrue('http://axschema.org/namePerson/last' in fetch_request)
        self.assertTrue(
            'http://axschema.org/namePerson/friendly' in fetch_request)
        # myOpenID compatibilty attributes:
        self.assertTrue(
            'http://schema.openid.net/contact/email' in fetch_request)
        self.assertTrue('http://schema.openid.net/namePerson' in fetch_request)
        self.assertTrue(
            'http://schema.openid.net/namePerson/friendly' in fetch_request)

        # Build up a response including AX data.
        openid_response = openid_request.answer(True)
        fetch_response = ax.FetchResponse(fetch_request)
        fetch_response.addValue('http://axschema.org/contact/email',
                                '*****@*****.**')
        fetch_response.addValue('http://axschema.org/namePerson/first',
                                'Firstname')
        fetch_response.addValue('http://axschema.org/namePerson/last',
                                'Lastname')
        fetch_response.addValue('http://axschema.org/namePerson/friendly',
                                'someuser')
        openid_response.addExtension(fetch_response)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in as testuser (the passed in
        # nickname has not caused the username to change).
        response = self.client.get('/getuser/')
        self.assertEqual(response.content, 'testuser')

        # The user's full name and email have been updated.
        user = User.objects.get(username='******')
        self.assertEqual(user.first_name, 'Firstname')
        self.assertEqual(user.last_name, 'Lastname')
        self.assertEqual(user.email, '*****@*****.**')
Exemplo n.º 30
0
    def test_login_attribute_exchange(self):
        settings.OPENID_UPDATE_DETAILS_FROM_SREG = True
        user = User.objects.create_user('testuser', '*****@*****.**')
        useropenid = UserOpenID(
            user=user,
            claimed_id='http://example.com/identity',
            display_id='http://example.com/identity')
        useropenid.save()

        # Configure the provider to advertise attribute exchange
        # protocol and start the authentication process:
        self.provider.type_uris.append('http://openid.net/srv/ax/1.0')
        response = self.client.post('/openid/login/',
            {'openid_identifier': 'http://example.com/identity',
             'next': '/getuser/'})
        self.assertContains(response, 'OpenID transaction in progress')

        # The resulting OpenID request uses the Attribute Exchange
        # extension rather than the Simple Registration extension.
        openid_request = self.provider.parseFormPost(response.content)
        sreg_request = sreg.SRegRequest.fromOpenIDRequest(openid_request)
        self.assertEqual(sreg_request.required, [])
        self.assertEqual(sreg_request.optional, [])

        fetch_request = ax.FetchRequest.fromOpenIDRequest(openid_request)
        self.assertTrue(fetch_request.has_key(
                'http://axschema.org/contact/email'))
        self.assertTrue(fetch_request.has_key(
                'http://axschema.org/namePerson'))
        self.assertTrue(fetch_request.has_key(
                'http://axschema.org/namePerson/first'))
        self.assertTrue(fetch_request.has_key(
                'http://axschema.org/namePerson/last'))
        self.assertTrue(fetch_request.has_key(
                'http://axschema.org/namePerson/friendly'))
        # myOpenID compatibilty attributes:
        self.assertTrue(fetch_request.has_key(
                'http://schema.openid.net/contact/email'))
        self.assertTrue(fetch_request.has_key(
                'http://schema.openid.net/namePerson'))
        self.assertTrue(fetch_request.has_key(
                'http://schema.openid.net/namePerson/friendly'))

        # Build up a response including AX data.
        openid_response = openid_request.answer(True)
        fetch_response = ax.FetchResponse(fetch_request)
        fetch_response.addValue(
            'http://axschema.org/contact/email', '*****@*****.**')
        fetch_response.addValue(
            'http://axschema.org/namePerson/first', 'Firstname')
        fetch_response.addValue(
            'http://axschema.org/namePerson/last', 'Lastname')
        fetch_response.addValue(
            'http://axschema.org/namePerson/friendly', 'someuser')
        openid_response.addExtension(fetch_response)
        response = self.complete(openid_response)
        self.assertRedirects(response, 'http://testserver/getuser/')

        # And they are now logged in as testuser (the passed in
        # nickname has not caused the username to change).
        response = self.client.get('/getuser/')
        self.assertEquals(response.content, 'testuser')

        # The user's full name and email have been updated.
        user = User.objects.get(username='******')
        self.assertEquals(user.first_name, 'Firstname')
        self.assertEquals(user.last_name, 'Lastname')
        self.assertEquals(user.email, '*****@*****.**')