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
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
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'))
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)
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 __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)
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
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
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'))
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 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)
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)
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)
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)
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
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
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)])
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
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
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')))
def get_extra_data(self, response): return SRegResponse.fromSuccessResponse(response)
def get_extra_data(self, response): return SRegResponse.fromSuccessResponse(response)
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 {}
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 {}
def process(self): """ Second part of the authentication. The OpenID provider service redirects to us with information in the URL regarding the status of the authentication on its side. """ # If the requested path belongs to the one defined for the # connection handlers then we do not performany verification if cherrypy.request.path_info.startswith(self.base_auth_path): return # If we are already authenticated then we don't apply this step # any further if self.is_authenticated(): info = cherrypy.session[self.session_name]["info"] sreg = cherrypy.session[self.session_name]["sreg"] cherrypy.request.openid = OpenIDResponse() cherrypy.request.openid.info = info cherrypy.request.openid.sreg = sreg return oidconsumer = consumer.Consumer(self.get_session(), self.store) cherrypy.session[self.session_name]["status"] = UNKNOWN cherrypy.request.openid = OpenIDResponse() # Ask the library to check the response that the server sent # us. Status is a code indicating the response type. info is # either None or a string containing more information about # the return type. info = oidconsumer.complete( query=cherrypy.request.params, current_url=cherrypy.session[self.session_name]["return_to"] ) sreg = SRegResponse.fromSuccessResponse(info) cherrypy.session[self.session_name]["info"] = info cherrypy.session[self.session_name]["sreg"] = sreg cherrypy.request.openid.info = info cherrypy.request.openid.sreg = sreg if info.status == consumer.FAILURE and info.identity_url: # In the case of failure, if info is non-None, it is the # URL that we were verifying. We include it in the error # message to help the user figure out what happened. raise cherrypy.HTTPRedirect(self.failed_authentication_path) elif info.status == consumer.SUCCESS: # Success means that the transaction completed without # error. If info is None, it means that the user cancelled # the verification. # This is a successful verification attempt. If this # was a real application, we would do our login, # comment posting, etc. here. if info.endpoint.canonicalID: # You should authorize i-name users by their canonicalID, # rather than their more human-friendly identifiers. That # way their account with you is not compromised if their # i-name registration expires and is bought by someone else. pass cherrypy.session[self.session_name]["status"] = AUTHENTICATED cherrypy.request.params = {} raise cherrypy.HTTPRedirect(cherrypy.url(cherrypy.request.path_info)) elif info.status == consumer.CANCEL: # cancelled raise cherrypy.HTTPRedirect(self.cancel_authentication_path) raise cherrypy.HTTPRedirect(self.error_authentication_path)
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
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
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 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')))
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 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)