Exemple #1
0
	def _parse_response(self, response):
		"""
		parses the response and return a dict of
		parameters.. the dict will be returned to 
		the view to redirect the user to some specific
		page..
		
		only caring about SUCCESS since i classify all
		other statuses as failure.

		"""
		
		params = {}
		
		if response.status == SUCCESS:
			sreg_response = SRegResponse.fromSuccessResponse(response)
			
			params["identifier"] = response.identity_url
			params["user_info"] = {} if not sreg_response else sreg_response.data
			params["link"] = self.link_on_success
		else:
			params["message"] = OPENID_FAILURE_MESSAGE
			params["link"] = self.link_on_fail
		
		return params
Exemple #2
0
    def test_login_create_users(self):
        settings.OPENID_CREATE_USERS = True
        # Create a user with the same name as we'll pass back via sreg.
        User.objects.create_user('someuser', '*****@*****.**')

        # 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 = SRegRequest.fromOpenIDRequest(openid_request)
        openid_response = openid_request.answer(True)
        sreg_response = 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 a new user (they haven't taken
        # over the existing "someuser" user).
        response = self.client.get('/getuser/')
        self.assertEquals(response.content, 'someuser2')

        # Check the details of the new user.
        user = User.objects.get(username='******')
        self.assertEquals(user.first_name, 'Some')
        self.assertEquals(user.last_name, 'User')
        self.assertEquals(user.email, '*****@*****.**')
  def Respond(self, oidresponse):
    logging.warning('Respond: oidresponse.request.mode ' + oidresponse.request.mode)

    if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']:
      user = users.get_current_user()
      if user:
        from openid.extensions.sreg import SRegRequest, SRegResponse
        sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request)
        if sreg_req.wereFieldsRequested():
          logging.info("sreg_req:%s", sreg_req.allRequestedFields())
          user_data = {'nickname':user.nickname(),
                       'email':user.email()}
          sreg_resp = SRegResponse.extractResponse(sreg_req, user_data)
          sreg_resp.toMessage(oidresponse.fields)        
    logging.info('Using response: %s' % oidresponse)
    encoded_response = oidserver.encodeResponse(oidresponse)

    for header, value in encoded_response.headers.items():
      self.response.headers[header] = str(value)

    if encoded_response.code in (301, 302):
      self.redirect(self.response.headers['location'])
    else:
      self.response.set_status(encoded_response.code)

    if encoded_response.body:
      logging.debug('Sending response body: %s' % encoded_response.body)
      self.response.out.write(encoded_response.body)
    else:
      self.response.out.write('')
Exemple #4
0
    def createPositiveResponse(self):
        """Create a positive assertion OpenIDResponse.

        This method should be called to create the response to
        successful checkid requests.

        If the trust root for the request is in openid_sreg_trustroots,
        then additional user information is included with the
        response.
        """
        assert self.account is not None, (
            'Must be logged in for positive OpenID response')
        assert self.openid_request is not None, (
            'No OpenID request to respond to.')

        if not self.isIdentityOwner():
            return self.createFailedResponse()

        if self.openid_request.idSelect():
            response = self.openid_request.answer(
                True, identity=self.user_identity_url)
        else:
            response = self.openid_request.answer(True)

        person = IPerson(self.account)
        sreg_fields = dict(
            nickname=person.name,
            email=person.preferredemail.email,
            fullname=self.account.displayname)
        sreg_request = SRegRequest.fromOpenIDRequest(self.openid_request)
        sreg_response = SRegResponse.extractResponse(
            sreg_request, sreg_fields)
        response.addExtension(sreg_response)

        return response
Exemple #5
0
    def test_login_create_users(self):
        settings.OPENID_CREATE_USERS = True
        # Create a user with the same name as we'll pass back via sreg.
        User.objects.create_user('someuser', '*****@*****.**')

        # 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 = SRegRequest.fromOpenIDRequest(openid_request)
        openid_response = openid_request.answer(True)
        sreg_response = 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 a new user (they haven't taken
        # over the existing "someuser" user).
        response = self.client.get('/getuser/')
        self.assertEquals(response.content, 'someuser2')

        # Check the details of the new user.
        user = User.objects.get(username='******')
        self.assertEquals(user.first_name, 'Some')
        self.assertEquals(user.last_name, 'User')
        self.assertEquals(user.email, '*****@*****.**')
Exemple #6
0
    def Respond(self, oidresponse):
        logging.warning('Respond: oidresponse.request.mode ' +
                        oidresponse.request.mode)

        if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']:
            user = users.get_current_user()
            if user:
                from openid.extensions.sreg import SRegRequest, SRegResponse
                sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request)
                if sreg_req.wereFieldsRequested():
                    logging.info("sreg_req:%s", sreg_req.allRequestedFields())
                    user_data = {
                        'nickname': user.nickname(),
                        'email': user.email()
                    }
                    sreg_resp = SRegResponse.extractResponse(
                        sreg_req, user_data)
                    sreg_resp.toMessage(oidresponse.fields)
        logging.info('Using response: %s' % oidresponse)
        encoded_response = oidserver.encodeResponse(oidresponse)

        for header, value in encoded_response.headers.items():
            self.response.headers[header] = str(value)

        if encoded_response.code in (301, 302):
            self.redirect(self.response.headers['location'])
        else:
            self.response.set_status(encoded_response.code)

        if encoded_response.body:
            logging.debug('Sending response body: %s' % encoded_response.body)
            self.response.out.write(encoded_response.body)
        else:
            self.response.out.write('')
Exemple #7
0
    def createPositiveResponse(self):
        """Create a positive assertion OpenIDResponse.

        This method should be called to create the response to
        successful checkid requests.

        If the trust root for the request is in openid_sreg_trustroots,
        then additional user information is included with the
        response.
        """
        assert self.account is not None, (
            'Must be logged in for positive OpenID response')
        assert self.openid_request is not None, (
            'No OpenID request to respond to.')

        if not self.isIdentityOwner():
            return self.createFailedResponse()

        if self.openid_request.idSelect():
            response = self.openid_request.answer(
                True, identity=self.user_identity_url)
        else:
            response = self.openid_request.answer(True)

        person = IPerson(self.account)
        sreg_fields = dict(nickname=person.name,
                           email=person.preferredemail.email,
                           fullname=self.account.displayname)
        sreg_request = SRegRequest.fromOpenIDRequest(self.openid_request)
        sreg_response = SRegResponse.extractResponse(sreg_request, sreg_fields)
        response.addExtension(sreg_response)

        return response
Exemple #8
0
  def Respond(self, oidresponse, sreg_req=False):
    """Send an OpenID response.

    Args:
      oidresponse: OpenIDResponse
      The response to send, usually created by OpenIDRequest.answer().
    """
    logging.warning('Respond: oidresponse.request.mode ' + oidresponse.request.mode)

    if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']:
      if sreg_req:
        sreg_resp = SRegResponse.extractResponse(sreg_req, {'email': self.user, 'nickname': self.user.rsplit('@',1)[0]})
        oidresponse.addExtension(sreg_resp)

    logging.debug('Using response: %s' % oidresponse)
    encoded_response = oidserver.encodeResponse(oidresponse)

    # update() would be nice, but wsgiref.headers.Headers doesn't implement it
    for header, value in encoded_response.headers.items():
      self.response.headers[header] = str(value)

    if encoded_response.code in (301, 302):
      self.redirect(self.response.headers['location'])
    else:
      self.response.set_status(encoded_response.code)

    if encoded_response.body:
      logging.debug('Sending response body: %s' % encoded_response.body)
      self.response.out.write(encoded_response.body)
    else:
      self.response.out.write('')
    def test_known_trust_roots_with_auto_authorize(self):
        # == Behaviour for known trust roots with auto_authorize ==

        # enable auto-authorize for the rpconfig
        allowed_user_attribs = ','.join(['fullname', 'email', 'timezone'])
        self.create_openid_rp_config(
            trust_root=self.consumer_url,
            allowed_user_attribs=allowed_user_attribs, auto_authorize=True)
        # Now begin another identical OpenID authentication request:
        response = self.initial_dance()

        # Again, the authentication request is successful:
        info = self.complete_from_response(response)

        self.assertEqual(info.status, 'success')
        self.assertEqual(info.endpoint.claimed_id, self.claimed_id)

        # Again, we have some user details, but this time, the optional
        # sreg fields are also included automatically.

        sreg_response = SRegResponse.fromSuccessResponse(info)

        self.assertEqual(list(sorted(sreg_response.items())),
                         [('email', self.account.preferredemail.email),
                          ('fullname', self.account.displayname)])
    def test_required_fields_checked(self):
        # = Restricted OpenID Simple Registration Extension support =

        # The Launchpad OpenID server has restricted support for the OpenID
        # Simple Registration Extension.  It will only provide a full set of
        # registration details to certain known trust roots.  The user's
        # launchpad username is share with all roots.

        # This is done in order to share the user details among the various
        # Canonical/Ubuntu sites participating in single sign-on.  The user's
        # nickname is published to every site, which is useful things like
        # weblog comments.

        # == Behaviour for unknown trust roots ==

        # If a relying party attempts to request user details via the
        # openid.sreg extension and Launchpad does not have a particular policy
        # configured, then only the user's approved fields are returned in the
        # response.

        response = self.initial_dance()
        # authorize data
        # required fields are checked by default. don't authorize anything
        fields = self.get_from_response(response, 'input[type="checkbox"]')
        self.assertEqual(len(fields), 3)
        for f in fields:
            self.assertFalse(f.get('disabled'))
            self.assertEqual(f.get('checked') == 'checked',
                             f.get('name') in self.required)

        # do not send any field in the post
        response = self.yes_to_decide(response)

        # We have authenticated successfully:
        info = self.complete_from_response(response)

        self.assertEqual(info.status, 'success')
        self.assertEqual(info.endpoint.claimed_id, self.claimed_id)

        # But no fields are returned:

        sreg_response = SRegResponse.fromSuccessResponse(info)

        self.assertEqual(sreg_response, None)

        # If we attempt to authenticate again, we will be prompted to
        # confirm which fields we want to provide to the RP again,
        # but the defaults will be what we provided last time:

        # No log in needed this time, we're directed straight to the confirm
        # screen.  Check that email is *not* selected by default this time:
        response = self.initial_dance(with_login=False)
        fields = self.get_from_response(response, 'input[type="checkbox"]')
        self.assertEqual(len(fields), 3)
        for f in fields:
            self.assertFalse(f.get('disabled'))
            self.assertFalse(f.get('checked'))
    def authenticateCredentials(self, credentials):
        """Authenticates credentials.

        If the credentials can be authenticated, return an object that provides
        IPrincipalInfo. If the plugin cannot authenticate the credentials,
        returns None.
        """
        if not IOpenIdCredentials.providedBy(credentials):
            return None

        if credentials.failed:
            return None

        if credentials.principalInfo is not None \
                and credentials.principalInfo.internalId in self:
            return credentials.principalInfo

        request = credentials.request

        consumer = Consumer(ISession(request)[SESSION_KEY], self.store)

        returnto = credentials.parameters.get(
            'openid.return_to', getReturnToURL(request))
        response = consumer.complete(
            credentials.parameters, returnto.split('?')[0])

        if isinstance(response, SuccessResponse):
            identifier = normalizeIdentifier(response.identity_url)
            principalId = self.getPrincipalByOpenIdIdentifier(identifier)
            if principalId is None:
                # Principal does not exist
                principal = OpenIdPrincipal()
                principal.identifier = identifier

                sregResponse = SRegResponse.fromSuccessResponse(response)

                name = INameChooser(self).chooseName('', principal)
                self[name] = principal
                principalId = self.getPrincipalByOpenIdIdentifier(identifier)

                # register principal in portal registration tool
                auth = getUtility(IAuthentication)
                pid = auth.prefix + self.prefix + name
                try:
                    principal = auth.getPrincipal(pid)
                    getUtility(IPortalRegistration).registerPrincipal(principal)
                except PrincipalLookupError:
                    pass

            principalInfo = self.principalInfo(self.prefix + principalId)
            credentials.principalInfo = principalInfo
            return principalInfo

        else:
            raise PrincipalInitializationFailed(response.message)

        return None
Exemple #12
0
    def login_complete(self):
        """This function is called once a user has succesfully logged in to
        his/her OpenID account. The user is then prompted to choose a
        preferred alias to be known as if a default one is not provided.
        """
        consumer = Consumer(session=session, store=self.openid_store)
        host = request.headers['host']
        return_url = url(host=host, controller='account',
            action='login_complete')
        result = consumer.complete(request.params, return_url)
        if result.status != 'success':
            return _('An error ocurred with login.')
        try:
            user = model.User.by_identifier(result.identity_url).one()
            session['userid'] = user.id
        except (AttributeError, NoResultFound):
            # No previous login record for the user.
            sreg_res = SRegResponse.fromSuccessResponse(result)
            try:
                email = sreg_res['email']
            except (TypeError, KeyError):
                email = ''

            try:
                name = sreg_res['nickname']
            except (TypeError, KeyError):
                name = result.identity_url
            user = model.User(
                name=name,
                identifier=result.identity_url,
                email=email
            )
            try:
                model.User.all()
            except NoResultFound:
                # Since you're going to be the only user, might as well grant
                # you administrator privileges.
                user.admin = True
            model.session.add(user)
            model.session.commit()
            session['userid'] = user.id
        session.save()
        if user.name == result.identity_url:
            h.flash(
                _('Login was successful, but now you need to set a name.'),
                'warning'
            )
            redirect(
                url(
                    controller='account',
                    action='profile',
                    id=user.id,
                    edit='true'
                )
            )
        redirect(url(controller='blog', action='index'))
Exemple #13
0
def handle_sreg(request, response):
    """Handle any sreg data requests"""
    sreg_req = SRegRequest.fromOpenIDRequest(request)
    # Extract information if required
    if sreg_req.wereFieldsRequested():
        fields = config.sreg_fields()
        if not fields:
            return
        sreg_resp = SRegResponse.extractResponse(sreg_req, config.sreg_fields())
        sreg_resp.toMessage(response.fields)
Exemple #14
0
    def __init__(self, resp, extensions):
        sreg_resp = SRegResponse.fromSuccessResponse(resp)
        self.sreg = sreg_resp and sreg_resp.data or {}
        self.ax_resp = ax.FetchResponse.fromSuccessResponse(resp) or {}

        # Process the OpenID response with the OpenIDResponse class provided
        self.ext = {}
        for extension in extensions:
            ext_name = getattr(extension, "ns_alias", extension.__name__)
            self.ext[ext_name] = extension.fromSuccessResponse(resp)
Exemple #15
0
 def sreg(self):
     """
     Try to get OpenID Simple Registation
     http://openid.net/specs/openid-simple-registration-extension-1_0.html
     """
     if self.resp:
         resp = self.resp
         sreg_resp = SRegResponse.fromSuccessResponse(resp)
         return sreg_resp.data if sreg_resp else None
     else:
         return None
Exemple #16
0
 def sreg(self):
     """
     Try to get OpenID Simple Registation
     http://openid.net/specs/openid-simple-registration-extension-1_0.html
     """
     if self.resp:
         resp = self.resp
         sreg_resp = SRegResponse.fromSuccessResponse(resp)
         return sreg_resp.data if sreg_resp else None
     else:
         return None
def from_openid_response(openid_response):
    issued = int(time.time())
 
    openid = OpenID(openid_response.identity_url, issued, openid_response.signed_fields)
    if getattr(settings, 'OPENID_SREG', False):
        openid.sreg = SRegResponse.fromSuccessResponse(openid_response)
 
    if getattr(settings, 'OPENID_AX', False):
        openid.ax = AXFetchResponse.fromSuccessResponse(openid_response)
 
    return openid
Exemple #18
0
    def __init__(self, resp, extensions):
        sreg_resp = SRegResponse.fromSuccessResponse(resp)
        self.sreg = sreg_resp and sreg_resp.data or {}
        self.ax_resp = ax.FetchResponse.fromSuccessResponse(resp) or {}

        # Process the OpenID response with the OpenIDResponse class provided
        self.ext = {}
        for extension in extensions:
            ext_name = getattr(extension, 'ns_alias', extension.__name__)
            self.ext[ext_name] = \
                extension.fromSuccessResponse(resp)
Exemple #19
0
  def Respond(self, oidresponse):
    """Send an OpenID response.

    Args:
      oidresponse: OpenIDResponse
      The response to send, usually created by OpenIDRequest.answer().
    """
    logging.warning('Respond: oidresponse.request.mode ' + oidresponse.request.mode)

    if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']:
      # user = users.get_current_user()
      user = self.get_current_user()
      if user:
        from openid.extensions.sreg import SRegRequest,SRegResponse
        sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request)
        logging.info("sreg_req:%s",sreg_req.allRequestedFields())
        if sreg_req.wereFieldsRequested():
          user_data = {'nickname':user.nickname,
                       'email':user.email}
          sreg_resp = SRegResponse.extractResponse(sreg_req, user_data)
          sreg_resp.toMessage(oidresponse.fields)
        # add nickname, using the Simple Registration Extension:
        # http://www.openidenabled.com/openid/simple-registration-extension/
        #oidresponse.fields.setArg('http://openid.net/sreg/1.0', 'nickname', user.nickname)
        #oidresponse.fields.setArg('http://openid.net/sreg/1.0', 'email', user.email)
        #oidresponse.fields.setArg('http://openid.net/srv/ax/1.0', 'nickname', user.nickname)
        #oidresponse.fields.setArg('http://openid.net/srv/ax/1.0', 'email', user.email)
        from openid.extensions.ax import FetchRequest, FetchResponse	
        res ={'nickname':user.nickname,'email':user.email,'attr0':user.email,'attr1':user.nickname}
        ax_req = FetchRequest.fromOpenIDRequest(oidresponse.request)
        logging.info("ax_req:%s",ax_req.getRequiredAttrs())
        ax_res = FetchResponse()
        for x in ax_req.iterAttrs():
          ax_res.addValue(x.type_uri,res[x.alias] )
        ax_res.toMessage(oidresponse.fields)       
        pass
    logging.info('Using response: %s' % oidresponse)
    encoded_response = oidserver.encodeResponse(oidresponse)

    # update() would be nice, but wsgiref.headers.Headers doesn't implement it
    for header, value in encoded_response.headers.items():
      self.response.headers[header] = str(value)

    if encoded_response.code in (301, 302):
      self.redirect(self.response.headers['location'])
    else:
      self.response.set_status(encoded_response.code)

    if encoded_response.body:
      logging.debug('Sending response body: %s' % encoded_response.body)
      self.response.out.write(encoded_response.body)
    else:
      self.response.out.write('')
Exemple #20
0
def openid_end(return_url, request):
    """Step two of logging in; the OpenID provider redirects back here."""

    cons = Consumer(session=request.session, store=openid_store)
    params = request.params

    if 'return_key' in params and not key_from_request(request):
        # We've followed a return_key that has terminated at the OpenID request
        # i.e. this is a stashed OpenID request (or a bogus return_key); the
        # OpenID request will therefore NOT have the return_key in its
        # return_to URL, so strip it
        log.debug("OpenID check stripping stale or bogus return_key(s) '{0}'"
                  .format(params.getall('return_key')))
        # Janrain OpenID treats params as a normal dict, so it's safe to lose
        # the MultiDict here (AFAICT).
        params = dict((k, v) for k, v in params.iteritems() if k != 'return_key')

    res = cons.complete(params, return_url)

    if res.status == SUCCESS:
        pass

    elif res.status == FAILURE:
        # The errors are, very helpfully, plain strings.  Nevermind that
        # there's a little hierarchy of exception classes inside the openid
        # library; they all get squashed into homogenous goo in the return
        # value.  F*****g awesome.  Check for a few common things here and
        # assume the rest are wacky internal errors
        log.error('openid failure: ' + res.message)

        if res.message == 'Nonce already used or out of range':
            # You tend to get this if you hit refresh on login_finish
            raise OpenIDError("Sorry!  Your login attempt expired; please start over.")
        else:
            raise OpenIDError("Something has gone hilariously wrong.")

    elif res.status == CANCEL:
        raise OpenIDError("Looks like you canceled the login.")

    else:
        log.error("Unexpected OpenID return status '{0}' with message '{1}'"
                  .format(res.status, res.message))
        raise OpenIDError("Something has gone hilariously wrong.")

    identity_url = unicode(res.identity_url)
    identity_webfinger = request.session.pop('pending_identity_webfinger', None)

    sreg_res = SRegResponse.fromSuccessResponse(res) or dict()
    pape_res = PAPEResponse.fromSuccessResponse(res)
    auth_time = pape_res.auth_time

    return identity_url, identity_webfinger, auth_time, sreg_res
Exemple #21
0
    def login_complete(self):
        """This function is called once a user has succesfully logged in to
        his/her OpenID account. The user is then prompted to choose a
        preferred alias to be known as if a default one is not provided.
        """
        consumer = Consumer(session=session, store=self.openid_store)
        host = request.headers['host']
        return_url = url(host=host,
                         controller='account',
                         action='login_complete')
        result = consumer.complete(request.params, return_url)
        if result.status != 'success':
            return _('An error ocurred with login.')
        try:
            user = model.User.by_identifier(result.identity_url).one()
            session['userid'] = user.id
        except (AttributeError, NoResultFound):
            # No previous login record for the user.
            sreg_res = SRegResponse.fromSuccessResponse(result)
            try:
                email = sreg_res['email']
            except (TypeError, KeyError):
                email = ''

            try:
                name = sreg_res['nickname']
            except (TypeError, KeyError):
                name = result.identity_url
            user = model.User(name=name,
                              identifier=result.identity_url,
                              email=email)
            try:
                model.User.all()
            except NoResultFound:
                # Since you're going to be the only user, might as well grant
                # you administrator privileges.
                user.admin = True
            model.session.add(user)
            model.session.commit()
            session['userid'] = user.id
        session.save()
        if user.name == result.identity_url:
            h.flash(_('Login was successful, but now you need to set a name.'),
                    'warning')
            redirect(
                url(controller='account',
                    action='profile',
                    id=user.id,
                    edit='true'))
        redirect(url(controller='blog', action='index'))
Exemple #22
0
def _get_email_from_response(response):
    email = None
    sreg = SRegResponse.fromSuccessResponse(response)
    if sreg:
        email = valid_email_or_none(sreg.get(SRegField.EMAIL))
    if not email:
        ax = FetchResponse.fromSuccessResponse(response)
        if ax:
            try:
                values = ax.get(AXAttribute.CONTACT_EMAIL)
                if values:
                    email = valid_email_or_none(values[0])
            except KeyError:
                pass
    return email
Exemple #23
0
def get_email_from_response(response):
    email = None
    sreg = SRegResponse.fromSuccessResponse(response)
    if sreg:
        email = valid_email_or_none(sreg.get(SRegField.EMAIL))
    if not email:
        ax = FetchResponse.fromSuccessResponse(response)
        if ax:
            try:
                values = ax.get(AXAttribute.CONTACT_EMAIL)
                if values:
                    email = valid_email_or_none(values[0])
            except KeyError:
                pass
    return email
 def process_response(self):
     resp = self.consumer.complete(self.environment.request.vars, self.return_to_url)
     if resp.status == openid.consumer.consumer.SUCCESS:
         sreg_resp = SRegResponse.fromSuccessResponse(resp)
         print sreg_resp.data
         self.environment.session.w2popenid.user_data = sreg_resp.data
         flash = 'OpenID authentication successfull.'
     if resp.status == openid.consumer.consumer.FAILURE:
         flash = 'OpenID authentication failed. (Error message: %s)' % resp.message
     if resp.status == openid.consumer.consumer.CANCEL:
         flash = 'OpenID authentication canceled by user.'
     if resp.status == openid.consumer.consumer.SETUP_NEEDED:
         flash = 'OpenID authentication needs to be setup by the user with the provider first.'
     self.environment.session.flash = flash
     redirect(self.environment.session.w2popenid.login_next)
Exemple #25
0
 def add_sreg_fields(self, oidresponse, user):
     """
     Add requested Simple Registration Extension fields to oidresponse
     and return it.
     """
     sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request)
     if sreg_req.wereFieldsRequested():
         logging.debug("respond: sreg_req:%s",
                       sreg_req.allRequestedFields())
         sreg_map = dict(
             ((key, val) for (key, val) in 
              {'nickname':user.nickname(), 'email':user.email()}.items()
              if key in sreg_req.allRequestedFields()))
         oidresponse.addExtension(
             SRegResponse.extractResponse(sreg_req, sreg_map))
     return oidresponse
Exemple #26
0
def finish_openid_login(request):
	del request.session["openid_login"]

	args = {k : v for k, v in request.GET.iteritems()}
	args.update({k : v for k, v in request.POST.iteritems()})

	consumer = get_consumer(request)
	return_to = urljoin(get_base_url(request), request.path)
	response = consumer.complete(args, return_to)

	if response.status != "success":
		raise PermissionDenied
	else:
		sreg = SRegResponse.fromSuccessResponse(response)
		request.session["authenticated_user"] = get_job_poster(response, sreg)
		return HttpResponseRedirect(return_to)
Exemple #27
0
 def add_sreg_fields(self, oidresponse, user):
     """
     Add requested Simple Registration Extension fields to oidresponse
     and return it.
     """
     sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request)
     if sreg_req.wereFieldsRequested():
         logging.debug("respond: sreg_req:%s",
                       sreg_req.allRequestedFields())
         sreg_map = dict(((key, val) for (key, val) in {
             'nickname': user.nickname(),
             'email': user.email()
         }.items() if key in sreg_req.allRequestedFields()))
         oidresponse.addExtension(
             SRegResponse.extractResponse(sreg_req, sreg_map))
     return oidresponse
Exemple #28
0
    def login_finish(self):
        """Step two of logging in; the OpenID provider redirects back here."""

        cons = Consumer(session=session, store=self.openid_store)
        host = request.headers['host']
        return_url = url(host=host,
                         controller='accounts',
                         action='login_finish')
        res = cons.complete(request.params, return_url)

        if res.status == CANCEL:
            # I guess..  just..  back to the homepage?
            h.flash(u"""Login canceled.""", icon='user-silhouette')
            redirect(url('/'))
        elif res.status != SUCCESS:
            return 'Error!  %s' % res.message

        try:
            # Grab an existing user record, if one exists
            q = meta.Session.query(users_model.User) \
                    .filter(users_model.User.openids.any(openid=res.identity_url))
            user = q.one()
        except NoResultFound:
            # Try to pull a name out of the SReg response
            sreg_res = SRegResponse.fromSuccessResponse(res)
            try:
                username = sreg_res['nickname']
            except (KeyError, TypeError):
                # KeyError if sreg has no nickname; TypeError if sreg is None
                username = '******'

            # Create db records
            user = users_model.User(name=username)
            meta.Session.add(user)

            openid = users_model.OpenID(openid=res.identity_url)
            user.openids.append(openid)

            meta.Session.commit()

        # Remember who's logged in, and we're good to go
        session['user_id'] = user.id
        session.save()

        h.flash(u"""Hello, {0}!""".format(user.name), icon='user')

        redirect(url('/'), code=303)
Exemple #29
0
    def login_finish(self):
        """Step two of logging in; the OpenID provider redirects back here."""

        cons = Consumer(session=session, store=self.openid_store)
        host = request.headers['host']
        return_url = url(host=host, controller='accounts', action='login_finish')
        res = cons.complete(request.params, return_url)

        if res.status == CANCEL:
            # I guess..  just..  back to the homepage?
            h.flash(u"""Login canceled.""", icon='user-silhouette')
            redirect(url('/'))
        elif res.status != SUCCESS:
            return 'Error!  %s' % res.message

        try:
            # Grab an existing user record, if one exists
            q = meta.Session.query(users_model.User) \
                    .filter(users_model.User.openids.any(openid=res.identity_url))
            user = q.one()
        except NoResultFound:
            # Try to pull a name out of the SReg response
            sreg_res = SRegResponse.fromSuccessResponse(res)
            try:
                username = sreg_res['nickname']
            except (KeyError, TypeError):
                # KeyError if sreg has no nickname; TypeError if sreg is None
                username = '******'

            # Create db records
            user = users_model.User(name=username)
            meta.Session.add(user)

            openid = users_model.OpenID(openid=res.identity_url)
            user.openids.append(openid)

            meta.Session.commit()

        # Remember who's logged in, and we're good to go
        session['user_id'] = user.id
        session.save()

        h.flash(u"""Hello, {0}!""".format(user.name),
                icon='user')

        redirect(url('/'), code=303)
Exemple #30
0
def _add_user_attribs(request, openid_request, openid_response):
    # Add ax and sreg result data
    sreg_request = SRegRequest.fromOpenIDRequest(openid_request)
    ax_request = ax.FetchRequest.fromOpenIDRequest(openid_request)
    rpconfig = utils.get_rpconfig(openid_request.trust_root)
    form = UserAttribsRequestForm(
        request, sreg_request, ax_request, rpconfig)
    if form.data_approved_for_request:
        sreg_response = SRegResponse.extractResponse(
            sreg_request, form.data_approved_for_request)
        openid_response.addExtension(sreg_response)
        if ax_request is not None:
            ax_response = ax.FetchResponse(ax_request)
            for k, v in form.data_approved_for_request.iteritems():
                if AX_DATA_FIELDS.getNamespaceURI(k) in ax_request:
                    ax_response.addValue(AX_DATA_FIELDS.getNamespaceURI(k), v)
            openid_response.addExtension(ax_response)
 def process_response(self):
     resp = self.consumer.complete(self.environment.request.vars, self.return_to_url)
     if resp.status == openid.consumer.consumer.SUCCESS:
         sreg_resp = SRegResponse.fromSuccessResponse(resp)
         #print sreg_resp.data
         #self.environment.session.w2popenid.user_data = sreg_resp.data
         #flash = 'OpenID authentication successfull. ' + sreg_resp.data
         flash = 'OpenID authentication successfull.'
         logging.debug('my function abc is starting') 
         #logging.error('huston we got a %s problem.' % 'major') 
 
     if resp.status == openid.consumer.consumer.FAILURE:
         flash = 'OpenID authentication failed. (Error message: %s)' % resp.message
     if resp.status == openid.consumer.consumer.CANCEL:
         flash = 'OpenID authentication canceled by user.'
     if resp.status == openid.consumer.consumer.SETUP_NEEDED:
         flash = 'OpenID authentication needs to be setup by the user with the provider first.'
     self.environment.session.flash = flash
Exemple #32
0
  def Respond(self, oidresponse):
    """Send an OpenID response.

    Args:
      oidresponse: OpenIDResponse
      The response to send, usually created by OpenIDRequest.answer().
    """
    logging.info('Respond: oidresponse.request.mode ' + oidresponse.request.mode)

    if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']:
      user = Auth.AuthenticatedUser(self.request)
      if user:
        from openid.extensions.sreg import SRegRequest,SRegResponse
        sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request)
        if sreg_req.wereFieldsRequested():
          logging.info("sreg_req:%s",sreg_req.allRequestedFields())
          user_data = {'nickname':user.nickname(),
                       'email':user.email}
          sreg_resp = SRegResponse.extractResponse(sreg_req, user_data)
          sreg_resp.toMessage(oidresponse.fields)        
        # add nickname, using the Simple Registration Extension:
        # http://www.openidenabled.com/openid/simple-registration-extension/
#mrk
#        oidresponse.fields.setArg('http://openid.net/sreg/1.0', 'nickname', user.nickname())
#        oidresponse.fields.setArg('http://openid.net/sreg/1.0', 'email', user.email())
        pass
    logging.info('Using response: %s' % oidresponse)
    encoded_response = oidserver.encodeResponse(oidresponse)

    # update() would be nice, but wsgiref.headers.Headers doesn't implement it
    for header, value in encoded_response.headers.items():
      self.response.headers[header] = str(value)

    if encoded_response.code in (301, 302):
      self.redirect(self.response.headers['location'])
    else:
      self.response.set_status(encoded_response.code)

    if encoded_response.body:
      logging.debug('Sending response body: %s' % encoded_response.body)
      self.response.out.write(encoded_response.body)
    else:
      self.response.out.write('')
Exemple #33
0
    def _complete_login(self, environ, start_response):
        """Complete the OpenID authentication process.

        Here we handle the result of the OpenID process.  If the process
        succeeded, we record the username in the session and redirect the user
        to the page they were trying to view that triggered the login attempt.
        In the various failures cases we return a 401 Unauthorized response
        with a brief explanation of what went wrong.
        """
        query = dict(parse_querystring(environ))
        # Passing query['openid.return_to'] here is massive cheating, but
        # given we control the endpoint who cares.
        response = self._make_consumer(environ).complete(
            query, query['openid.return_to'])
        if response.status == SUCCESS:
            self.log.error('open id response: SUCCESS')
            sreg_info = SRegResponse.fromSuccessResponse(response)
            if not sreg_info:
                self.log.error('sreg_info is None.')
                exc = HTTPUnauthorized()
                exc.explanation = (
                    "You don't have a Launchpad account. Check that you're "
                    "logged in as the right user, or log into Launchpad and try "
                    "again.")
                raise exc
            environ[self.session_var]['identity_url'] = response.identity_url
            environ[self.session_var]['user'] = sreg_info['nickname']
            raise HTTPMovedPermanently(query['back_to'])
        elif response.status == FAILURE:
            self.log.error('open id response: FAILURE: %s', response.message)
            exc = HTTPUnauthorized()
            exc.explanation = response.message
            raise exc
        elif response.status == CANCEL:
            self.log.error('open id response: CANCEL')
            exc = HTTPUnauthorized()
            exc.explanation = "Authentication cancelled."
            raise exc
        else:
            self.log.error('open id response: UNKNOWN')
            exc = HTTPUnauthorized()
            exc.explanation = "Unknown OpenID response."
            raise exc
Exemple #34
0
    def _complete_login(self, environ, start_response):
        """Complete the OpenID authentication process.

        Here we handle the result of the OpenID process.  If the process
        succeeded, we record the username in the session and redirect the user
        to the page they were trying to view that triggered the login attempt.
        In the various failures cases we return a 401 Unauthorized response
        with a brief explanation of what went wrong.
        """
        query = dict(parse_querystring(environ))
        # Passing query['openid.return_to'] here is massive cheating, but
        # given we control the endpoint who cares.
        response = self._make_consumer(environ).complete(
            query, query['openid.return_to'])
        if response.status == SUCCESS:
            self.log.error('open id response: SUCCESS')
            sreg_info = SRegResponse.fromSuccessResponse(response)
            if not sreg_info:
                self.log.error('sreg_info is None.')
                exc = HTTPUnauthorized()
                exc.explanation = (
                  "You don't have a Launchpad account. Check that you're "
                  "logged in as the right user, or log into Launchpad and try "
                  "again.")
                raise exc
            environ[self.session_var]['user'] = sreg_info['nickname']
            raise HTTPMovedPermanently(query['back_to'])
        elif response.status == FAILURE:
            self.log.error('open id response: FAILURE: %s', response.message)
            exc = HTTPUnauthorized()
            exc.explanation = response.message
            raise exc
        elif response.status == CANCEL:
            self.log.error('open id response: CANCEL')
            exc = HTTPUnauthorized()
            exc.explanation = "Authentication cancelled."
            raise exc
        else:
            self.log.error('open id response: UNKNOWN')
            exc = HTTPUnauthorized()
            exc.explanation = "Unknown OpenID response."
            raise exc
    def test_known_trust_root(self):
        # == Behaviour for known trust roots ==

        # If we create a Relying Party configuration for the trust root, things
        # play out a bit differently:

        allowed_user_attribs = ','.join(['fullname', 'nickname',
                                         'email', 'timezone'])
        self.create_openid_rp_config(
            trust_root=self.consumer_url,
            allowed_user_attribs=allowed_user_attribs)

        # Now begin another identical OpenID authentication request:
        response = self.initial_dance()
        # authorize data
        # required fields cannot be unchecked.
        fields = self.get_from_response(response, 'input[type="checkbox"]')
        self.assertEqual(len(fields), 3)
        for f in fields:
            self.assertEqual(f.get('disabled') == 'disabled',
                             f.get('name') in self.required)
            self.assertTrue(f.get('checked'))

        # authorize nickname
        # unauthorize fullname (checked by default)
        response = self.yes_to_decide(response, nickname=True)

        # Again, the authentication request is successful:
        info = self.complete_from_response(response)

        self.assertEqual(info.status, 'success')
        self.assertEqual(info.endpoint.claimed_id, self.claimed_id)

        # But now we have some user details.
        sreg_response = SRegResponse.fromSuccessResponse(info)
        self.assertEqual(list(sorted(sreg_response.items())),
                         [('email', self.account.preferredemail.email),
                          ('nickname', self.account.person.name)])
Exemple #36
0
def get_value_from_response(response, sreg_names=None, ax_names=None):
    value = None
    if sreg_names:
        sreg = SRegResponse.fromSuccessResponse(response)
        if sreg:
            for name in sreg_names:
                value = sreg.get(name)
                if value:
                    break

    if not value and ax_names:
        ax = FetchResponse.fromSuccessResponse(response)
        if ax:
            for name in ax_names:
                try:
                    values = ax.get(name)
                    if values:
                        value = values[0]
                except KeyError:
                    pass
                if value:
                    break
    return value
Exemple #37
0
def get_value_from_response(response, sreg_names=None, ax_names=None):
    value = None
    if sreg_names:
        sreg = SRegResponse.fromSuccessResponse(response)
        if sreg:
            for name in sreg_names:
                value = sreg.get(name)
                if value:
                    break

    if not value and ax_names:
        ax = FetchResponse.fromSuccessResponse(response)
        if ax:
            for name in ax_names:
                try:
                    values = ax.get(name)
                    if values:
                        value = values[0]
                except KeyError:
                    pass
                if value:
                    break
    return value
Exemple #38
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 = SRegRequest.fromOpenIDRequest(openid_request)
        openid_response = openid_request.answer(True)
        sreg_response = 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, '*****@*****.**')
Exemple #39
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 = SRegRequest.fromOpenIDRequest(openid_request)
        openid_response = openid_request.answer(True)
        sreg_response = 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, '*****@*****.**')
Exemple #40
0
    def process_authentication_request(self, request):
        consumer = Consumer(request.session, OsqaOpenIDStore())

        query_dict = dict([
            (k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items()
        ])

        #for i in query_dict.items():
            #print "%s : %s" % i

        url = get_url_host(request) + request.path
        openid_response = consumer.complete(query_dict, url)

        if openid_response.status == SUCCESS:

            consumer_data = {}

            sreg_attrs = getattr(self, 'sreg_attributes', False)

            if sreg_attrs:
                sreg_response = SRegResponse.fromSuccessResponse(openid_response)

                if sreg_response:
                    all_attrs = {}
                    [all_attrs.update(d) for k,d in sreg_attrs.items() if k != "policy_url"]

                    for attr_name, local_name in all_attrs.items():
                        if attr_name in sreg_response:
                            consumer_data[local_name] = sreg_response[attr_name]

            ax_schema = getattr(self, 'dataype2ax_schema', False)

            if ax_schema:
                ax = AXFetchResponse.fromSuccessResponse(openid_response)

                if ax:
                    axargs = ax.getExtensionArgs()

                    ax_schema2data_type = dict([(s, t) for t, s in ax_schema.items()])

                    available_types = dict([
                        (ax_schema2data_type[s], re.sub('^type\.', '', n))
                        for n, s in axargs.items() if s in ax_schema2data_type
                    ])

                    for t, s in available_types.items():
                        if not t in consumer_data:
                            if axargs.get("value.%s.1" % s, None):
                                consumer_data[t] = axargs["value.%s.1" % s]
                    
            request.session['auth_consumer_data'] = consumer_data


            return request.GET['openid.identity']
        elif openid_response.status == CANCEL:
            raise InvalidAuthentication(_('The OpenId authentication request was canceled'))
        elif openid_response.status == FAILURE:
            raise InvalidAuthentication(_('The OpenId authentication failed: ') + openid_response.message)
        elif openid_response.status == SETUP_NEEDED:
            raise InvalidAuthentication(_('Setup needed'))
        else:
            raise InvalidAuthentication(_('The OpenId authentication failed with an unknown status: ') + openid_response.status)
 def __init__(self, resp):
     sreg_resp = SRegResponse.fromSuccessResponse(resp)
     self.sreg = sreg_resp and sreg_resp.data or {}
     self.ax_resp = ax.FetchResponse.fromSuccessResponse(resp) or {}
Exemple #42
0
        # Create a directed identity if needed
        if identity == IDENTIFIER_SELECT:
            hash = hashlib.sha1(str(request.user.id)+'|'+orequest.trust_root) \
                    .hexdigest()
            claimed_id = request.build_absolute_uri(
                    reverse('openid-provider-identity', args=[hash]))
            logger.info('Giving directed identity %r to trusted root %r \
with sreg data %s' % (claimed_id, orequest.trust_root, user_data))
        else:
            claimed_id = identity
            logger.info('Giving claimed identity %r to trusted root %r \
with sreg data %s' % (claimed_id, orequest.trust_root, user_data))

        oresponse = orequest.answer(True, identity=claimed_id)
        sreg_response = SRegResponse.extractResponse(sreg_request, user_data)
        oresponse.addExtension(sreg_response)
    else:
        oresponse = server.handleRequest(orequest)
    logger.info('Returning OpenID response %s' % oresponse)
    return oresponse_to_response(server, oresponse)

def openid_xrds(request, identity=False, id=None):
    '''XRDS discovery page'''
    logger.debug('OpenID XRDS identity:%(identity)s id:%(id)s' % locals())
    if identity:
        types = [OPENID_2_0_TYPE, OPENID_1_0_TYPE, OPENID_1_1_TYPE, SREG_TYPE]
        local_ids = []
    else:
        types = [OPENID_IDP_2_0_TYPE,SREG_TYPE]
        local_ids = []
Exemple #43
0
 def __init__(self, resp):
     sreg_resp = SRegResponse.fromSuccessResponse(resp)
     self.sreg = sreg_resp and sreg_resp.data or {}
     self.ax_resp = ax.FetchResponse.fromSuccessResponse(resp) or {}
Exemple #44
0
def _response_nickname(response):
    """ Gets the nickname from the OpenID providers response"""
    sreg_response = SRegResponse.fromSuccessResponse(response)
    if sreg_response and 'nickname' in sreg_response:
        return sreg_response.data['nickname']
    return None
Exemple #45
0
        # Create a directed identity if needed
        if identity == IDENTIFIER_SELECT:
            hash = hashlib.sha1(str(request.user.id)+'|'+orequest.trust_root) \
                    .hexdigest()
            claimed_id = request.build_absolute_uri(
                    reverse('openid-provider-identity', args=[hash]))
            logger.info('Giving directed identity %r to trusted root %r \
with sreg data %s' % (claimed_id, orequest.trust_root, user_data))
        else:
            claimed_id = identity
            logger.info('Giving claimed identity %r to trusted root %r \
with sreg data %s' % (claimed_id, orequest.trust_root, user_data))

        oresponse = orequest.answer(True, identity=claimed_id)
        sreg_response = SRegResponse.extractResponse(sreg_request, user_data)
        oresponse.addExtension(sreg_response)
    else:
        oresponse = server.handleRequest(orequest)
    logger.info('Returning OpenID response %s' % oresponse)
    return oresponse_to_response(server, oresponse)

def openid_xrds(request, identity=False, id=None):
    '''XRDS discovery page'''
    logger.debug('OpenID XRDS identity:%(identity)s id:%(id)s' % locals())
    if identity:
        types = [OPENID_2_0_TYPE, OPENID_1_0_TYPE, OPENID_1_1_TYPE, SREG_TYPE]
        local_ids = []
    else:
        types = [OPENID_IDP_2_0_TYPE,SREG_TYPE]
        local_ids = []
Exemple #46
0
 def get_extra_data(self, response):
     return SRegResponse.fromSuccessResponse(response)
Exemple #47
0
    def process_authentication_request(self, request):
        consumer = Consumer(request.session, OsqaOpenIDStore())

        query_dict = dict([(smart_unicode(k), smart_unicode(v))
                           for k, v in request.GET.items()])

        #for i in query_dict.items():
        #print "%s : %s" % i

        url = get_url_host(request) + request.path
        openid_response = consumer.complete(query_dict, url)

        if openid_response.status == SUCCESS:

            consumer_data = {}

            sreg_attrs = getattr(self, 'sreg_attributes', False)

            if sreg_attrs:
                sreg_response = SRegResponse.fromSuccessResponse(
                    openid_response)

                if sreg_response:
                    all_attrs = {}
                    [
                        all_attrs.update(d) for k, d in sreg_attrs.items()
                        if k != "policy_url"
                    ]

                    for attr_name, local_name in all_attrs.items():
                        if attr_name in sreg_response:
                            consumer_data[local_name] = sreg_response[
                                attr_name]

            ax_schema = getattr(self, 'dataype2ax_schema', False)

            if ax_schema:
                ax = AXFetchResponse.fromSuccessResponse(
                    openid_response, False)

                if ax:
                    axargs = ax.getExtensionArgs()

                    ax_schema2data_type = dict([(s, t)
                                                for t, s in ax_schema.items()])

                    available_types = dict([(ax_schema2data_type[s],
                                             re.sub('^type\.', '', n))
                                            for n, s in axargs.items()
                                            if s in ax_schema2data_type])

                    for t, s in available_types.items():
                        if not t in consumer_data:
                            if axargs.get("value.%s.1" % s, None):
                                consumer_data[t] = axargs["value.%s.1" % s]

            request.session['auth_consumer_data'] = consumer_data

            return request.GET['openid.identity']
        elif openid_response.status == CANCEL:
            raise InvalidAuthentication(
                _('The OpenId authentication request was canceled'))
        elif openid_response.status == FAILURE:
            raise InvalidAuthentication(
                _('The OpenId authentication failed: ') +
                openid_response.message)
        elif openid_response.status == SETUP_NEEDED:
            raise InvalidAuthentication(_('Setup needed'))
        else:
            raise InvalidAuthentication(
                _('The OpenId authentication failed with an unknown status: ')
                + openid_response.status)
Exemple #48
0
def _response_email(response):
    """ Gets the email from the OpenID providers response"""
    sreg_response = SRegResponse.fromSuccessResponse(response)
    if sreg_response and 'email' in sreg_response:
        return sreg_response.data['email']
    return None
 def get_extra_data(self, response):
     return SRegResponse.fromSuccessResponse(response)
Exemple #50
0
 def from_sreg():
     sreg_response = SRegResponse.fromSuccessResponse(openid_info)
     if sreg_response is not None:
         return smart_unicode(sreg_response.get('nickname', sreg_response.get('fullname')))
Exemple #51
0
def openid_auth_site(request):
    try:
        oreq = request.session['openid_request']
    except KeyError:
        return render(request,
                      'openid-auth-site.html', {
                          'error':
                          'No OpenID request associated. The request may have \
            expired.',
                      },
                      status=400)

    sreg = SRegRequest.fromOpenIDRequest(oreq)
    ax = FetchRequest.fromOpenIDRequest(oreq)

    sreg_fields = set(sreg.allRequestedFields())
    if ax:
        for uri in ax.requested_attributes:
            k = openid_ax_attribute_mapping.get(uri)
            if k:
                sreg_fields.add(k)

    ldap_user = LDAPUser.objects.get(username=request.user.username)
    if sreg_fields:
        sreg_data = {
            'nickname': ldap_user.username,
            'email': ldap_user.email,
            'fullname': ldap_user.full_name,
            'dob': ldap_user.birthday,
        }

        for k in list(sreg_data):
            if not sreg_data[k]:
                del sreg_data[k]
    else:
        sreg_data = {}
    sreg_fields = sreg_data.keys()

    # Read preferences from the db.
    try:
        saved_pref = OpenID_Attributes.objects.get(
            uid=ldap_user.uid,
            trust_root=oreq.trust_root,
        )
    except OpenID_Attributes.DoesNotExist:
        saved_pref = None
        auto_auth = False
    else:
        auto_auth = saved_pref.always_auth

    if auto_auth or request.POST:
        if auto_auth:
            # TODO: can we do this nicer?
            form_inp = model_to_dict(saved_pref)
        else:
            form_inp = request.POST
        form = SiteAuthForm(form_inp, instance=saved_pref)
        # can it be invalid somehow?
        assert (form.is_valid())
        attrs = form.save(commit=False)

        # nullify fields that were not requested
        for fn in form.cleaned_data:
            if fn in ('always_auth', ):
                pass
            elif hasattr(attrs, fn) and fn not in sreg_fields:
                setattr(attrs, fn, None)

        if auto_auth or 'accept' in request.POST:
            # prepare sreg response
            for fn, send in form.cleaned_data.items():
                if fn not in sreg_data:
                    pass
                elif not send:
                    del sreg_data[fn]
                elif isinstance(sreg_data[fn], list):
                    form_key = 'which_%s' % fn
                    val = form.cleaned_data[form_key]
                    if val not in sreg_data[fn]:
                        raise NotImplementedError(
                            'Changing choices not implemented yet')
                    sreg_data[fn] = val
                    if not auto_auth:
                        setattr(attrs, form_key, val)

            if not auto_auth:
                # save prefs in the db
                # (if auto_auth, then nothing changed)
                attrs.uid = ldap_user.uid
                attrs.trust_root = oreq.trust_root
                attrs.save()

            oresp = oreq.answer(True,
                                identity=request.build_absolute_uri(
                                    reverse(user_page,
                                            args=(request.user.username, ))))

            sreg_resp = SRegResponse.extractResponse(sreg, sreg_data)
            oresp.addExtension(sreg_resp)

            if ax:
                ax_resp = FetchResponse(ax)
                for uri in ax.requested_attributes:
                    k = openid_ax_attribute_mapping.get(uri)
                    if k and k in sreg_data:
                        ax_resp.addValue(uri, sreg_data[k])
                oresp.addExtension(ax_resp)
        elif 'reject' in request.POST:
            oresp = oreq.answer(False)
        else:
            return render(request,
                          'openid-auth-site.html', {
                              'error': 'Invalid request submitted.',
                          },
                          status=400)

        if request.session.get('auto_logout', False):
            # _logout clears request.session
            _logout(request)
        else:
            del request.session['openid_request']
        return render_openid_response(request, oresp)

    form = SiteAuthForm(instance=saved_pref)
    sreg_form = {}
    # Fill in lists for choices
    for f in sreg_fields:
        if f not in sreg_data:
            pass
        elif isinstance(sreg_data[f], list):
            form.fields['which_%s' % f].widget.choices = [
                (x, x) for x in sreg_data[f]
            ]
            sreg_form[f] = form['which_%s' % f]
        else:
            sreg_form[f] = format_html(
                "<input type='text'" + " readonly='readonly'" +
                " value='{0}' />", sreg_data[f])

    try:
        # TODO: cache it
        if oreq.returnToVerified():
            tr_valid = 'Return-To valid and trusted'
        else:
            tr_valid = 'Return-To untrusted'
    except openid.yadis.discover.DiscoveryFailure:
        tr_valid = 'Unable to verify trust (Yadis unsupported)'
    except openid.fetchers.HTTPFetchingError:
        tr_valid = 'Unable to verify trust (HTTP error)'

    return render(
        request, 'openid-auth-site.html', {
            'openid_request': oreq,
            'return_to_valid': tr_valid,
            'form': form,
            'sreg': sreg_fields,
            'sreg_form': sreg_form,
            'policy_url': sreg.policy_url,
        })