当前位置: 首页>>代码示例>>Python>>正文


Python SRegResponse.fromSuccessResponse方法代码示例

本文整理汇总了Python中openid.extensions.sreg.SRegResponse.fromSuccessResponse方法的典型用法代码示例。如果您正苦于以下问题:Python SRegResponse.fromSuccessResponse方法的具体用法?Python SRegResponse.fromSuccessResponse怎么用?Python SRegResponse.fromSuccessResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在openid.extensions.sreg.SRegResponse的用法示例。


在下文中一共展示了SRegResponse.fromSuccessResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _parse_response

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
	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
开发者ID:refik,项目名称:raptiye,代码行数:27,代码来源:openid_consumer.py

示例2: test_known_trust_roots_with_auto_authorize

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
    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)])
开发者ID:miing,项目名称:mci_migo,代码行数:27,代码来源:test_restricted_sreg.py

示例3: authenticateCredentials

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
    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
开发者ID:Zojax,项目名称:zojax.principal.openid,代码行数:59,代码来源:plugin.py

示例4: test_required_fields_checked

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
    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'))
开发者ID:miing,项目名称:mci_migo,代码行数:59,代码来源:test_restricted_sreg.py

示例5: login_complete

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
    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'))
开发者ID:chrisrsantiago,项目名称:muse,代码行数:58,代码来源:account.py

示例6: __init__

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
    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)
开发者ID:Mondego,项目名称:pyreco,代码行数:12,代码来源:allPythonContent.py

示例7: from_openid_response

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
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
开发者ID:Zojax,项目名称:zojax.django.socialauthentication,代码行数:13,代码来源:utils.py

示例8: sreg

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
 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
开发者ID:Flinou,项目名称:UPMC-PSTL,代码行数:13,代码来源:openid_auth.py

示例9: openid_end

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
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.  Fucking 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
开发者ID:eevee,项目名称:floof,代码行数:54,代码来源:openid_.py

示例10: get_email_from_response

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
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
开发者ID:pennersr,项目名称:django-allauth,代码行数:17,代码来源:utils.py

示例11: process_response

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
 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)
开发者ID:pombredanne,项目名称:webserver-web2py,代码行数:17,代码来源:w2popenid.py

示例12: login_finish

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
    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 = 'Anonymous'

            # 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)
开发者ID:encukou,项目名称:spline,代码行数:48,代码来源:accounts.py

示例13: process_response

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
 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
开发者ID:pombredanne,项目名称:webserver-web2py,代码行数:20,代码来源:w2popenid.py

示例14: _complete_login

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
    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
开发者ID:abramhindle,项目名称:UnnaturalCodeFork,代码行数:44,代码来源:app.py

示例15: test_known_trust_root

# 需要导入模块: from openid.extensions.sreg import SRegResponse [as 别名]
# 或者: from openid.extensions.sreg.SRegResponse import fromSuccessResponse [as 别名]
    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)])
开发者ID:miing,项目名称:mci_migo,代码行数:40,代码来源:test_restricted_sreg.py


注:本文中的openid.extensions.sreg.SRegResponse.fromSuccessResponse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。