def google_signin(request): """ This is the view where the Google account login icon on your site points to, e.g. http://www.yourdomain.com/google-signin """ consumer = Consumer(request.session, DjangoOpenIDStore()) # catch Google Apps domain that is referring, if any _domain = None if 'domain' in request.POST: _domain = request.POST['domain'] elif 'domain' in request.GET: _domain = request.GET['domain'] try: # two different endpoints depending on whether the using is using Google Account or Google Apps Account if _domain: auth_request = consumer.begin('https://www.google.com/accounts/o8/site-xrds?hd=%s' % _domain) else: auth_request = consumer.begin('https://www.google.com/accounts/o8/id') except DiscoveryFailure as e: return CustomError(request, "Google Accounts Error", "Google's OpenID endpoint is not available.") # add requests for additional account information required, in my case: email, first name & last name auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'mode', 'fetch_request') auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'required', 'email,firstname,lastname') auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'type.email', 'http://schema.openid.net/contact/email') auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'type.firstname', 'http://axschema.org/namePerson/first') auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'type.lastname', 'http://axschema.org/namePerson/last') return redirect(auth_request.redirectURL('http://localhost', 'http://localhost/post_login'))
def _1(request): consumer = Consumer(request.session, DjangoOpenIDStore()) realm = "http://" + request.get_host() redirect_url = "http://" + request.get_host() + reverse('flexible_auth:auth-process', args=[cls.SERVICE_NAME, step+1]) # catch Google Apps domain that is referring, if any _domain = None if 'domain' in request.POST: _domain = request.POST['domain'] elif 'domain' in request.GET: _domain = request.GET['domain'] try: # two different endpoints depending on whether the using is using Google Account or Google Apps Account if _domain: auth_request = consumer.begin(cls.GOOGLE_APPS_URL % _domain) else: auth_request = consumer.begin(cls.GOOGLE_URL) except DiscoveryFailure as e: return CustomError(request, "Google Accounts Error", "Google's OpenID endpoint is not available.") # add requests for additional account information required, in this case: email, first name & last name + oauth token auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'mode', 'fetch_request') auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'required', 'email,firstname,lastname') auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'type.email', 'http://schema.openid.net/contact/email') auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'type.firstname', 'http://axschema.org/namePerson/first') auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'type.lastname', 'http://axschema.org/namePerson/last') return redirect(auth_request.redirectURL(realm, redirect_url))
def login(self): consumer = Consumer(session, SOOpenIDStore()) # catch Google Apps domain that is referring, if any domain = None if 'domain' in request.POST: domain = request.POST['domain'] elif 'domain' in request.GET: domain = request.GET['domain'] try: # two different endpoints depending on whether the using is using Google Account or Google Apps Account if domain: auth_request = consumer.begin('https://www.google.com/accounts/o8/site-xrds?hd=%s' % domain) else: auth_request = consumer.begin('https://www.google.com/accounts/o8/id') except DiscoveryFailure as e: flash ("Google Accounts Error : Google's OpenID endpoint is not available.") return redirect("/user/show_login") # add requests for additional account information required, in my case: email auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'mode', 'fetch_request') auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'required', 'email') auth_request.addExtensionArg('http://openid.net/srv/ax/1.0', 'type.email', 'http://schema.openid.net/contact/email') return redirect(auth_request.redirectURL(url('/', qualified=True), url(controller='user', action='google_login_response', qualified=True)))
def link_google(self, registration): openid_session = session.get("openid_session", {}) openid_store = None # stateless cons = Consumer(openid_session, openid_store) GOOGLE_OPENID = 'https://www.google.com/accounts/o8/id' try: authrequest = cons.begin(GOOGLE_OPENID) except DiscoveryFailure: h.flash(_('Authentication failed, please try again.')) redirect(registration.url(action='personal_info')) ax_req = ax.FetchRequest() ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/first', alias='firstname', required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/last', alias='lastname', required=True)) ax_req.add(ax.AttrInfo('http://schema.openid.net/contact/email', alias='email', required=True)) authrequest.addExtension(ax_req) session['openid_session'] = openid_session session.save() realm = url(controller='home', action='index', qualified=True) return_to = registration.url(action='google_verify', qualified=True) redirect(authrequest.redirectURL(realm, return_to))
def process_request(self, request): if request.path_info[0:7] != '/admin/': return None if 'openid_username' not in request.session: request.session['openid_session'] = {} consumer = Consumer(request.session['openid_session'], None) # auth request to google has not been made yet if 'openid.mode' not in request.REQUEST: ax_request = ax.FetchRequest() ax_request.add(ax.AttrInfo('http://axschema.org/contact/email', required = True)) auth_request = consumer.begin('https://www.google.com/accounts/o8/id') auth_request.addExtension(ax_request) url = auth_request.redirectURL( request.build_absolute_uri('/'), return_to=request.build_absolute_uri()) return redirect(url) # auth request has been made, thus analyse google response else: info = consumer.complete(request.REQUEST, request.build_absolute_uri()) if info.status == SUCCESS: ax_response = ax.FetchResponse.fromSuccessResponse(info) username = ax_response.get('http://axschema.org/contact/email')[0] request.session['openid_username'] = username username = request.session.get('openid_username', None) if username not in AUTHORIZED_EMAILS: if username: del request.session['openid_username'] return HttpResponse('403 Forbidden', status=403)
def __call__(self): request = self.request siteURL = u'%s/'%absoluteURL(getSite(), request) if not IUnauthenticatedPrincipal.providedBy(request.principal): request.response.redirect(siteURL) return u'' if not 'openid_form_submitted' in request: request.response.redirect(siteURL) return u'' identifier = request.get('openid_identifier') if not identifier: IStatusMessage(request).add( _(u"Please specify your OpenID identifier.")) request.response.redirect(siteURL) return u'' authenticator = getUtility(IOpenIdAuthenticator) session = ISession(request)[SESSION_KEY] consumer = Consumer(session, authenticator.store) try: authRequest = consumer.begin(identifier) redirectURL = authRequest.redirectURL( siteURL, getReturnToURL(request)) except Exception, err: IStatusMessage(request).add(err, 'error') redirectURL = siteURL
def begin_openid(request, openid_url, redirect_field_name=REDIRECT_FIELD_NAME, redirect=None, return_view_name='openid_auth-complete_openid_login', sreg=None, extension_args=None): """ Setup the openid Consumer and redirect to the openid URL. """ #Set up the openid authorization request consumer = Consumer(request.session, DjangoOpenIDStore()) openid_auth = consumer.begin(openid_url) #Add openid extension args (for things like simple registration) extension_args = extension_args or {} #If we want simple registration, set the correct extension argument if sreg: extension_args['sreg.optional'] = sreg for name, value in extension_args.items(): namespace, key = name.split('.', 1) openid_auth.addExtensionArg(namespace, key, value) #Get the host to authenticate for trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_openid_return_host(request) + '/') #Make sure we have a full return URL and that we append any redirect parameters to it openid_return_url = get_openid_return_url(request, return_view_name=return_view_name, redirect_field_name=redirect_field_name, redirect=redirect) #Redirect to the authentication service openid_redirect_url = openid_auth.redirectURL(trust_root, openid_return_url) return HttpResponseRedirect(openid_redirect_url)
def google_login(self): openid_session = session.get("openid_session", {}) openid_store = None # stateless cons = Consumer(openid_session, openid_store) GOOGLE_OPENID = 'https://www.google.com/accounts/o8/id' openid = GOOGLE_OPENID try: authrequest = cons.begin(openid) except DiscoveryFailure: h.flash(_('Authentication failed, please try again.')) redirect(c.came_from or url(controller='home', action='index')) ax_req = ax.FetchRequest() ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/first', alias='firstname', required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/last', alias='lastname', required=True)) ax_req.add(ax.AttrInfo('http://schema.openid.net/contact/email', alias='email', required=True)) authrequest.addExtension(ax_req) kargs = self._auth_args() redirecturl = authrequest.redirectURL( url('frontpage', qualified=True), return_to=url(controller='federation', action='google_verify', qualified=True, **kargs)) session['openid_session'] = openid_session session.save() redirect(redirecturl)
def openid_select(request): oidutil.log = dummyOpenIdLoggingFunction if request.method != 'GET': return HttpResponseServerError("Invalid Input") try: action = request.GET['action'] openid_identifier = request.GET['openid_identifier'] except KeyError: return HttpResponseServerError("Invalid Input") if(action != 'verify'): return HttpResponseServerError("Invalid Input") openid_consumer = Consumer(request.session, CassandraStore()) try: auth_request = openid_consumer.begin(openid_identifier) except DiscoveryFailure: messages.error(request, 'Invalid OpenID URL') return redirect('users.views.login') ax_req = ax.FetchRequest() ax_req.add(ax.AttrInfo('http://axschema.org/contact/email', alias='email', required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/first', alias='firstname', required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/last', alias='lastname', required=True)) auth_request.addExtension(ax_req) realm = settings.OPENID_REALM redirect_url = auth_request.redirectURL(realm=realm, return_to=request.build_absolute_uri(reverse('users.views.openid_return'))) return redirect(redirect_url)
def libopenid(request, domain): if request.user is not None and request.user.is_authenticated(): return redirect(to="http://%s/" % request.get_host()) if domain is "default": discovery_url = "https://www.google.com/accounts/o8/id" else: discovery_url = "https://www.google.com/accounts/o8/site-xrds?hd=%s" % domain consumer = Consumer(request.session, FileOpenIDStore("/tmp/gtugdemo")) auth_request = consumer.begin(discovery_url) ax_request = ax.FetchRequest() ax_request.add(ax.AttrInfo("http://axschema.org/namePerson/first", required=True)) ax_request.add(ax.AttrInfo("http://axschema.org/namePerson/last", required=True)) ax_request.add(ax.AttrInfo("http://schema.openid.net/contact/email", required=True)) auth_request.addExtension(ax_request) realm = "http://%s/" % str(request.get_host()) logging.warn("REAL: %s" % realm) redirect_url = auth_request.redirectURL(realm=realm, return_to="http://%s/login/callback" % request.get_host()) """ oauth_query = { 'openid.ns.oauth': 'http://specs.openid.net/extensions/oauth/1.0', 'openid.oauth.consumer': request.get_host(), 'openid.oauth.scope': ' '.join(OAUTH_SCOPE), } redirect_url += "&%s" % urlencode(oauth_query) """ logging.warn(redirect_url) return redirect(to=redirect_url)
def try_login(self, identity_url, ask_for=None): """This tries to login with the given identity URL. This function must be called from the login_handler. The `ask_for` parameter can be a set of values to be asked from the openid provider. The following strings can be used in the `ask_for` parameter: ``aim``, ``blog``, ``country``, ``dob`` (date of birth), ``email``, ``fullname``, ``gender``, ``icq``, ``image``, ``jabber``, ``language``, ``msn``, ``nickname``, ``phone``, ``postcode``, ``skype``, ``timezone``, ``website``, ``yahoo`` """ if ask_for and __debug__: for key in ask_for: if key not in ALL_KEYS: raise ValueError('invalid key %r' % key) try: oidutil.log("self.store_factory() :" + str(self.store_factory)) consumer = Consumer(SessionWrapper(self), self.store_factory()) auth_request = consumer.begin(identity_url) if ask_for: self.attach_reg_info(auth_request, ask_for) except discover.DiscoveryFailure: self.signal_error(u'The OpenID was invalid') return redirect(self.get_current_url()) trust_root = request.host_url return redirect(auth_request.redirectURL(request.host_url, self.get_success_url()))
def login_begin(self): """Step one of logging in with OpenID; we redirect to the provider""" cons = Consumer(session=session, store=self.openid_store) try: openid_url = request.params['openid_identifier'] except KeyError: return self._bail("Gotta enter an OpenID to log in.") try: auth_request = cons.begin(openid_url) except DiscoveryFailure: return self._bail( "Can't connect to '{0}'. You sure it's an OpenID?".format( openid_url)) sreg_req = SRegRequest(optional=[ 'nickname', 'email', 'dob', 'gender', 'country', 'language', 'timezone' ]) auth_request.addExtension(sreg_req) host = request.headers['host'] protocol = request_config().protocol return_url = url(host=host, controller='accounts', action='login_finish') new_url = auth_request.redirectURL(return_to=return_url, realm=protocol + '://' + host) redirect(new_url)
def try_login(self, identity_url, ask_for=None): """This tries to login with the given identity URL. This function must be called from the login_handler. The `ask_for` parameter can be a set of values to be asked from the openid provider. The following strings can be used in the `ask_for` parameter: ``aim``, ``blog``, ``country``, ``dob`` (date of birth), ``email``, ``fullname``, ``gender``, ``icq``, ``image``, ``jabber``, ``language``, ``msn``, ``nickname``, ``phone``, ``postcode``, ``skype``, ``timezone``, ``website``, ``yahoo`` """ if ask_for and __debug__: for key in ask_for: if key not in ALL_KEYS: raise ValueError('invalid key %r' % key) try: consumer = Consumer(session, self.store_factory()) auth_request = consumer.begin(identity_url) if ask_for: self.attach_reg_info(auth_request, ask_for) except discover.DiscoveryFailure: self.signal_error(u'The OpenID was invalid') return redirect(self.get_current_url()) trust_root = request.host_url return redirect( auth_request.redirectURL(request.host_url, self.get_success_url()))
def ask_openid(request, openid_url=None, next_url=None, on_failure=None): """ basic function to ask openid and return response """ on_failure = on_failure or signin_failure sreg_request = sreg.SRegRequest(optional=["nickname", "email"]) trust_root = getattr(settings, "OPENID_TRUST_ROOT", get_url_host(request) + "/") if xri.identifierScheme(openid_url) == "XRI" and getattr(settings, "OPENID_DISALLOW_INAMES", False): msg = _("i-names are not supported") logging.debug("openid failed because i-names are not supported") return on_failure(request, msg) consumer = Consumer(request.session, util.DjangoOpenIDStore()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure: msg = _(u"OpenID %(openid_url)s is invalid" % {"openid_url": openid_url}) logging.debug(msg) return on_failure(request, msg) logging.debug("openid seemed to work") if sreg_request: logging.debug("adding sreg_request - wtf it is?") auth_request.addExtension(sreg_request) redirect_to = "%s%s?%s" % ( get_url_host(request), reverse("user_complete_openid_signin"), urllib.urlencode({"next": next_url}), ) redirect_url = auth_request.redirectURL(trust_root, redirect_to) logging.debug("redirecting to %s" % redirect_url) return HttpResponseRedirect(redirect_url)
def ask_openid( request, openid_url, redirect_to, on_failure=None, sreg_request=None ): """ basic function to ask openid and return response """ on_failure = on_failure or signin_failure trust_root = getattr( settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/' ) if xri.identifierScheme(openid_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False ): msg = _("i-names are not supported") logging.debug('openid failed because i-names are not supported') return on_failure(request, msg) consumer = Consumer(request.session, util.DjangoOpenIDStore()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure: msg = _(u"OpenID %(openid_url)s is invalid" % {'openid_url':openid_url}) logging.debug(msg) return on_failure(request, msg) logging.debug('openid seemed to work') if sreg_request: logging.debug('adding sreg_request - wtf it is?') auth_request.addExtension(sreg_request) redirect_url = auth_request.redirectURL(trust_root, redirect_to) logging.debug('redirecting to %s' % redirect_url) return HttpResponseRedirect(redirect_url)
def __call__(self, *args, **kw): request = self.request context = self.context siteURL = u'%s/'%absoluteURL(context, request) if not IUnauthenticatedPrincipal.providedBy(request.principal): self.redirect(siteURL) return u'' if not 'openid_form_submitted' in request: self.redirect(siteURL) return u'' identifier = request.get('openid_identifier') if not identifier or identifier == 'http://': IStatusMessage(request).add( _(u"Please specify your OpenID identifier.")) self.redirect(u'%slogin.html'%siteURL) return u'' authenticator = getUtility(IUsersPlugin) session = ISession(request)[SESSION_KEY] consumer = Consumer(session, authenticator.store) try: authRequest = consumer.begin(identifier) redirectURL = authRequest.redirectURL( siteURL, getReturnToURL(request)) except Exception, err: IStatusMessage(request).add(err, 'error') self.redirect(u'%slogin.html'%siteURL) return u''
def libopenid(request, domain): if request.user is not None and request.user.is_authenticated(): return redirect(to="http://%s/" % request.get_host()) if domain is 'default': discovery_url = "https://www.google.com/accounts/o8/id" else: discovery_url = "https://www.google.com/accounts/o8/site-xrds?hd=%s" % domain consumer = Consumer(request.session, FileOpenIDStore('/tmp/gtugdemo')) auth_request = consumer.begin(discovery_url) ax_request = ax.FetchRequest() ax_request.add(ax.AttrInfo('http://axschema.org/namePerson/first',required=True)) ax_request.add(ax.AttrInfo('http://axschema.org/namePerson/last',required=True)) ax_request.add(ax.AttrInfo('http://axschema.org/contact/email',required=True)) auth_request.addExtension(ax_request) redirect_url = auth_request.redirectURL(realm='http://%s/' % request.get_host(), return_to='http://%s/login/callback' % request.get_host()) oauth_query = { 'openid.ns.oauth': 'http://specs.openid.net/extensions/oauth/1.0', 'openid.oauth.consumer': request.get_host(), 'openid.oauth.scope': ' '.join(OAUTH_SCOPE), } redirect_url += "&%s" % urlencode(oauth_query) print redirect_url #print str(request.session.keys()) #return render_to_response('login.html', locals(), context_instance=RequestContext(request)) return redirect(to=redirect_url)
def get_auth_redirect_url(cls, identifier): s = FileOpenIDStore(cherrypy.request.app.config['appSettings']['openid.datastore_directory']) consumer = Consumer(session=cherrypy.session, store=s) authRequest = consumer.begin(identifier) return authRequest.redirectURL( realm=ApplicationPaths.get_site_root(), return_to=ApplicationPaths.get_handle_openid_auth_response_path())
def _fn(*args, **kwargs): if not session.get('logged_in', False): c = Consumer(session, openid_store) url = c.begin(openid_identity).redirectURL(url_for('index', _external=True), url_for('verify_identity', _external=True)) return redirect(url) else: return fn(*args, **kwargs)
def begin(request, openid_url): request.session['request_referer'] = urlparse.urljoin(request.META.get('HTTP_REFERER', ''), '/') consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure: return on_failure(request, _('The OpenID was invalid')) s = SRegRequest() for sarg in OPENID_SREG: if sarg.lower().lstrip() == "policy_url": s.policy_url = OPENID_SREG[sarg] else: for v in OPENID_SREG[sarg].split(','): s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required")) auth_request.addExtension(s) axr = AXFetchRequest() for i in OPENID_AX: axr.add(AttrInfo(i['type_uri'], i['count'], i['required'], i['alias'])) auth_request.addExtension(axr) redirect_url = auth_request.redirectURL(get_trusted_root(request), request.build_absolute_uri(reverse("openid_complete"))) return HttpResponseRedirect(redirect_url)
def ask_openid(request, openid_url, redirect_to, on_failure=None, sreg_request=None): """ basic function to ask openid and return response """ on_failure = on_failure or signin_failure trust_root = getattr( settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/' ) if xri.identifierScheme(openid_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False ): msg = _("i-names are not supported") return on_failure(request, msg) consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure: msg = _("The OpenID %s was invalid" % openid_url) return on_failure(request, msg) if sreg_request: auth_request.addExtension(sreg_request) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url)
def login_begin(self): """Step one of logging in with OpenID; we redirect to the provider""" cons = Consumer(session=session, store=self.openid_store) try: openid_url = request.params['openid_identifier'] except KeyError: return self._bail("Gotta enter an OpenID to log in.") try: auth_request = cons.begin(openid_url) except DiscoveryFailure: return self._bail( "Can't connect to '{0}'. You sure it's an OpenID?" .format(openid_url) ) sreg_req = SRegRequest(optional=['nickname', 'email', 'dob', 'gender', 'country', 'language', 'timezone']) auth_request.addExtension(sreg_req) host = request.headers['host'] protocol = request_config().protocol return_url = url(host=host, controller='accounts', action='login_finish') new_url = auth_request.redirectURL(return_to=return_url, realm=protocol + '://' + host) redirect(new_url)
def ask_openid(request, openid_url, redirect_to, on_failure=None, sreg_request=None): """ basic function to ask openid and return response """ request.encoding = 'UTF-8' on_failure = on_failure or signin_failure trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/') if xri.identifierScheme(openid_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): msg = _("i-names are not supported") return on_failure(request, msg) consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure: msg = _(u"OpenID %(openid_url)s is invalid" % {'openid_url': openid_url}) return on_failure(request, msg) if sreg_request: auth_request.addExtension(sreg_request) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url)
def ask_openid(request, openid_url, redirect_to, on_failure=None, sreg_request=None): """ basic function to ask openid and return response """ on_failure = on_failure or signin_failure trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/') if xri.identifierScheme(openid_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): msg = _("i-names are not supported") logging.debug('openid failed because i-names are not supported') return on_failure(request, msg) consumer = Consumer(request.session, util.DjangoOpenIDStore()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure: msg = _(u"OpenID %(openid_url)s is invalid" % {'openid_url': openid_url}) logging.debug(msg) return on_failure(request, msg) logging.debug('openid seemed to work') if sreg_request: logging.debug('adding sreg_request - wtf it is?') auth_request.addExtension(sreg_request) redirect_url = auth_request.redirectURL(trust_root, redirect_to) logging.debug('redirecting to %s' % redirect_url) return HttpResponseRedirect(redirect_url)
def signin(request, redirect_to=None): trust_root = getattr( settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/' ) # foo derbis. redirect_to = redirect_to or reverse('openid_complete') # In case they were lazy... if not redirect_to.startswith('http://') or redirect_to.startswith('https://'): redirect_to = get_url_host(request) + redirect_to if request.GET.get('next') and is_valid_next_url(request.GET['next']): if '?' in redirect_to: join = '&' else: join = '?' redirect_to += join + urllib.urlencode({ 'next': request.GET['next'] }) if xri.identifierScheme(STEAM_PROVIDER_URL) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False ): return on_failure(request, 'i-names are not supported') consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(STEAM_PROVIDER_URL) except DiscoveryFailure: return on_failure(request, 'The OpenID was invalid') redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url)
def try_login(self, identity_url, ask_for=None, ask_for_optional=None, extensions=None, immediate=False): """This tries to login with the given identity URL. This function must be called from the login_handler. The `ask_for` and `ask_for_optional`parameter can be a set of values to be asked from the openid provider, where keys in `ask_for` are marked as required, and keys in `ask_for_optional` are marked as optional. The following strings can be used in the `ask_for` and `ask_for_optional` parameters: ``aim``, ``blog``, ``country``, ``dob`` (date of birth), ``email``, ``fullname``, ``gender``, ``icq``, ``image``, ``jabber``, ``language``, ``msn``, ``nickname``, ``phone``, ``postcode``, ``skype``, ``timezone``, ``website``, ``yahoo`` `extensions` can be a list of instances of OpenID extension requests that should be passed on with the request. If you use this, please make sure to pass the Response classes of these extensions when initializing OpenID. `immediate` can be used to indicate this request should be a so-called checkid_immediate request, resulting in the provider not showing any UI. Note that this adds a new possible response: SetupNeeded, which is the server saying it doesn't have enough information yet to authorized or reject the authentication (probably, the user needs to sign in or approve the trust root). """ if ask_for and __debug__: for key in ask_for: if key not in ALL_KEYS: raise ValueError('invalid key %r' % key) if ask_for_optional: for key in ask_for_optional: if key not in ALL_KEYS: raise ValueError('invalid optional key %r' % key) try: consumer = Consumer(SessionWrapper(self), self.store_factory()) auth_request = consumer.begin(identity_url) if ask_for or ask_for_optional: self.attach_reg_info(auth_request, ask_for, ask_for_optional) if extensions: for extension in extensions: auth_request.addExtension(extension) except discover.DiscoveryFailure: self.signal_error(u'The OpenID was invalid') return redirect(self.get_current_url()) if self.url_root_as_trust_root: trust_root = request.url_root else: trust_root = request.host_url return redirect( auth_request.redirectURL(trust_root, self.get_success_url(), immediate=immediate))
def begin(request, sreg=None, extension_args=None, redirect_to=None, on_failure=None): on_failure = on_failure or default_on_failure extension_args = extension_args or {} if sreg: extension_args['sreg.optional'] = sreg trust_root = getattr( settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/' ) redirect_to = redirect_to or getattr( settings, 'OPENID_REDIRECT_TO', # If not explicitly set, assume current URL with complete/ appended get_full_url(request).split('?')[0] + 'complete/' ) # In case they were lazy... if not redirect_to.startswith('http://'): redirect_to = get_url_host(request) + redirect_to if request.GET.get('next') and is_valid_next_url(request.GET['next']): if '?' in redirect_to: join = '&' else: join = '?' redirect_to += join + urllib.urlencode({ 'next': request.GET['next'] }) user_url = request.POST.get('openid_url', None) if not user_url: request_path = request.path if request.GET.get('next'): request_path += '?' + urllib.urlencode({ 'next': request.GET['next'] }) return on_failure(request, "You didn't submit an OpenID URL") if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False ): return on_failure(request, 'i-names are not supported') user_url = oidutil.normalizeUrl(user_url) if not User.objects.filter(oid_url=user_url): return on_failure(request, "That is not a known OpenID URL. Please read <a href='/accounts/'>about accounts</a>") consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: return on_failure(request, "The OpenID was invalid") # Add extension args (for things like simple registration) for name, value in extension_args.items(): namespace, key = name.split('.', 1) auth_request.addExtensionArg(namespace, key, value) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url)
def ask_openid(request, openid_url, redirect_to, on_failure=None): on_failure = on_failure or signin_failure sreg_req = None ax_req = None _openid_url = openid_url trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/') if xri.identifierScheme(openid_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): msg = ("i-names are not supported") auth_oidlogin.send(sender=None, openid_url=_openid_url, state='not_supported') return on_failure(request, msg) consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure: msg = ("The OpenID %s was invalid") % openid_url auth_oidlogin.send(sender=None, openid_url=_openid_url, state='invalid') return on_failure(request, msg) # get capabilities use_ax, use_sreg = discover_extensions(openid_url) if use_sreg: # set sreg extension # we always ask for nickname and email sreg_attrs = getattr(settings, 'OPENID_SREG', {}) sreg_attrs.update({"optional": ['nickname', 'email']}) sreg_req = sreg.SRegRequest(**sreg_attrs) if use_ax: # set ax extension # we always ask for nickname and email ax_req = ax.FetchRequest() ax_req.add( ax.AttrInfo('http://schema.openid.net/contact/email', alias='email', required=True)) ax_req.add( ax.AttrInfo('http://schema.openid.net/namePerson/friendly', alias='nickname', required=True)) # add custom ax attrs ax_attrs = getattr(settings, 'OPENID_AX', []) for attr in ax_attrs: if len(attr) == 2: ax_req.add(ax.AttrInfo(attr[0], required=alias[1])) else: ax_req.add(ax.AttrInfo(attr[0])) if sreg_req is not None: auth_request.addExtension(sreg_req) if ax_req is not None: auth_request.addExtension(ax_req) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url)
def login(request): "Display the login form and handle the login action." try: del request.session['account_id'] except KeyError: # request.session did not have a has_key() last I checked... pass just_signed_up = False openid_failure = '' if request.POST: data = request.POST.copy() # don't validate fields that the user might have filled in before # changing the type.. if data.get('method', 'email') == 'email': data['openid'] = '' else: data['email'] = '' data['password'] = '' data['confirm_password'] = '' form = LoginForm(data) if form.is_valid(): if data.get('method', 'email') == 'email': account = form.get_account() request.session['account_id'] = account.id account.last_login = datetime.datetime.now() account.save() return HttpResponseRedirect('/feeds/unread/') else: openid = form.get_openid() consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(openid) except DiscoveryFailure: openid_failure = "The OpenID was invalid" else: trust_root = 'http://'+settings.SEYMOUR_DOMAIN + '/' redirect_to = 'http://'+settings.SEYMOUR_DOMAIN+'/login/openid/' redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url) else: initial = {'method': 'email'} form = LoginForm(initial=initial) return render_to_response('accounts/login.html', { 'form': form, 'just_signed_up': just_signed_up, 'openid_failure': openid_failure, 'section': 'login', 'method': request.POST.get('method', 'email') }, context_instance=RequestContext(request))
def openid_start(request): openid_url = "https://www.google.com/accounts/o8/id" store = FileOpenIDStore(settings.OPENID_STORE) consumer = Consumer(request.session, store) auth_request = consumer.begin(openid_url) # XXX: production. Handle errors! auth_request.addExtension(makeOpenIDAXRequest()) auth_request.addExtension(OpenIDUIExtension(mode="popup", icon=False)) url = auth_request.redirectURL(request.build_absolute_uri("/"), request.build_absolute_uri(reverse("openid_done"))) return HttpResponseRedirect(url)
def step1_get_authorize_url(self, openid_url, callback_url): """Returns a URI to redirect to the provider. """ consumer = Consumer(self.session, self.store) # if consumer discovery or authentication fails, show error page try: request = consumer.begin(openid_url) except Exception, e: raise e
def signin(request, sreg=None, extension_args={}, on_failure=default_on_failure): openid_url = None if is_valid_next_url(request.GET.get('next')): next = request.GET['next'] elif is_valid_next_url(get_address(request.META.get('HTTP_REFERER'), request)): next = get_address(request.META['HTTP_REFERER'], request) else: next = getattr(settings, 'OPENID_REDIRECT_NEXT', '/') def get_with_next(url, next): if next: return '%s?%s' % (url, urlencode({'next': next})) else: return url if request.user.is_authenticated() and 'force' not in request.GET: return HttpResponseRedirect(next) request_path = get_with_next(request.path, next) if request.method == 'POST': form = OpenidSigninForm(request.POST, auto_id='id_%s') if form.is_valid(): # first remove email and nickname from sreg if the are in to prevent dup extension_args['sreg.optional'] = 'email,nickname' if sreg: sreg = ','.join([arg for arg in sreg.split(',') if arg not in extension_args['sreg.optional']]) extension_args['sreg.optional'] += ',' + sreg trust_root = getattr(settings, 'OPENID_TRUST_ROOT', absolutize_uri(request, '/')) redirect_to = get_with_next(absolutize_uri(request, reverse('openid_complete')), next) if xri.identifierScheme(form.cleaned_data['openid_url']) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): return on_failure(request, _("i-names are not supported")) consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(form.cleaned_data['openid_url']) except DiscoveryFailure: return on_failure(request, _("The OpenID was invalid")) # Add extension args (for things like simple registration) for name, value in extension_args.items(): namespace, key = name.split('.', 1) auth_request.addExtensionArg(namespace, key, value) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url) else: form = OpenidSigninForm(auto_id='id_%s') return { 'form': form, 'action': request_path, }
def begin(request, sreg=None, extension_args=None, redirect_to=None, on_failure=None, if_not_user_url=None): on_failure = on_failure or default_on_failure if_not_user_url = if_not_user_url or default_if_not_user_url if request.GET.get('logo'): # Makes for a better demo return logo(request) extension_args = extension_args or {} if sreg: extension_args['sreg.optional'] = sreg trust_root = getattr( settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/' ) redirect_to = redirect_to or getattr( settings, 'OPENID_REDIRECT_TO', # If not explicitly set, assume current URL with complete/ appended get_full_url(request).split('?')[0] + 'complete/' ) # In case they were lazy... if not redirect_to.startswith('http://'): redirect_to = get_url_host(request) + redirect_to if request.GET.get('next') and is_valid_next_url(request.GET['next']): if '?' in redirect_to: join = '&' else: join = '?' redirect_to += join + urllib.urlencode({ 'next': request.GET['next'] }) user_url = request.REQUEST.get('openid_url', None) if not user_url: return if_not_user_url(request) if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False ): return on_failure(request, 'i-names are not supported') consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: return on_failure(request, "The OpenID was invalid") # Add extension args (for things like simple registration) for name, value in extension_args.items(): namespace, key = name.split('.', 1) auth_request.addExtensionArg(namespace, key, value) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url)
def perform_login(self, request, openid_identifier): try: consumer = Consumer(request.session, SolaceOpenIDStore()) auth_request = consumer.begin(openid_identifier) except discover.DiscoveryFailure: raise LoginUnsucessful(_(u'The OpenID was invalid')) trust_root = request.host_url redirect_to = url_for('core.login', openid_complete='yes', next=request.next_url, _external=True) return redirect(auth_request.redirectURL(trust_root, redirect_to))
def signin(request, sreg=None, extension_args={}, on_failure=default_on_failure): openid_url = None if is_valid_next_url(request.GET.get("next")): next = request.GET["next"] elif is_valid_next_url(get_address(request.META.get("HTTP_REFERER"), request)): next = get_address(request.META["HTTP_REFERER"], request) else: next = getattr(settings, "OPENID_REDIRECT_NEXT", "/") def get_with_next(url, next): if next: return "%s?%s" % (url, urlencode({"next": next})) else: return url if request.user.is_authenticated() and "force" not in request.GET: return HttpResponseRedirect(next) request_path = get_with_next(request.path, next) if request.method == "POST": form = OpenidSigninForm(request.POST, auto_id="id_%s") if form.is_valid(): # first remove email and nickname from sreg if the are in to prevent dup extension_args["sreg.optional"] = "email,nickname" if sreg: sreg = ",".join([arg for arg in sreg.split(",") if arg not in extension_args["sreg.optional"]]) extension_args["sreg.optional"] += "," + sreg trust_root = getattr(settings, "OPENID_TRUST_ROOT", absolutize_uri(request, "/")) redirect_to = get_with_next(absolutize_uri(request, reverse("openid_complete")), next) if xri.identifierScheme(form.cleaned_data["openid_url"]) == "XRI" and getattr( settings, "OPENID_DISALLOW_INAMES", False ): return on_failure(request, _("i-names are not supported")) consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(form.cleaned_data["openid_url"]) except DiscoveryFailure: return on_failure(request, _("The OpenID was invalid")) # Add extension args (for things like simple registration) for name, value in extension_args.items(): namespace, key = name.split(".", 1) auth_request.addExtensionArg(namespace, key, value) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url) else: form = OpenidSigninForm(auto_id="id_%s") return {"form": form, "action": request_path}
def begin(request, sreg=None, extension_args=None, redirect_to=None, on_failure=None): on_failure = on_failure or default_on_failure if request.GET.get('logo'): # Makes for a better demo return HttpResponse(OPENID_LOGO_BASE_64.decode('base64'), mimetype='image/gif') extension_args = extension_args or {} if sreg: extension_args['sreg.optional'] = sreg trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/') redirect_to = redirect_to or getattr( settings, 'OPENID_REDIRECT_TO', # If not explicitly set, assume current URL with complete/ appended get_full_url(request).split('?')[0] + 'complete/') # In case they were lazy... if not redirect_to.startswith('http://'): redirect_to = get_url_host(request) + redirect_to if request.GET.get('next') and is_valid_next_url(request.GET['next']): if '?' in redirect_to: join = '&' else: join = '?' redirect_to += join + 'next=' + urllib.urlencode(request.GET['next']) user_url = request.POST.get('openid_url', None) if not user_url: return render('openid_signin.html', {'action': request.path}) if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): return on_failure(request, 'i-names are not supported') consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: return on_failure(request, "The OpenID was invalid") # Add extension args (for things like simple registration) for name, value in extension_args.items(): namespace, key = name.split('.', 1) auth_request.addExtensionArg(namespace, key, value) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url)
def OpenIDStartSubmit(request, default_success_url='/', success_handler=None): response = django.http.HttpResponse() openid = request.REQUEST.get('openid_identifier', '').strip() if not openid: return err_page("no_openid_identifier") c = Consumer({}, store.DatastoreStore()) try: auth_request = c.begin(openid) except discover.DiscoveryFailure, e: return err_page("server_discovery", msg = 'OpenID discovery error with begin on %s: %s' % (openid, str(e)))
def begin_openid_login( request, openid_url, redirect_field_name=REDIRECT_FIELD_NAME, redirect=None, return_view_name='openid_auth.views.complete_openid_login', sreg=None, extension_args=None): """ Setup the openid Consumer and redirect to the openid URL. """ #Set up the openid authorization request consumer = Consumer(request.session, DjangoOpenIDStore()) openid_auth = consumer.begin(openid_url) #Check if the openId provider is allowed if hasattr(settings, 'OPENID_PROVIDERS') and settings.OPENID_PROVIDERS: found = False for provider_name in settings.OPENID_PROVIDERS: if provider_name in openid_auth.endpoint.server_url: found = True break if not found: error_message = "%s: %s" % (_("Not allowed OpenID provider"), openid_auth.endpoint.server_url) return failure_openid_login( request, openid_url, error_message, redirect_field_name=redirect_field_name) #Add openid extension args (for things like simple registration) extension_args = extension_args or {} #If we want simple registration, set the correct extension argument if sreg: extension_args['sreg.optional'] = sreg for name, value in extension_args.items(): namespace, key = name.split('.', 1) openid_auth.addExtensionArg(namespace, key, value) #Get the host to authenticate for trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_openid_return_host(request) + '/') #Make sure we have a full return URL and that we append any redirect parameters to it openid_return_url = get_openid_return_url( request, return_view_name=return_view_name, redirect_field_name=redirect_field_name, redirect=redirect) #Redirect to the authentication service openid_redirect_url = openid_auth.redirectURL(trust_root, openid_return_url) return HttpResponseRedirect(openid_redirect_url)
def prepare_authentication_request(self, request, redirect_to): if not redirect_to.startswith('http://') or redirect_to.startswith( 'https://'): redirect_to = get_url_host(request) + redirect_to user_url = self.get_user_url(request) if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): raise InvalidAuthentication('i-names are not supported') consumer = Consumer(request.session, OsqaOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: raise InvalidAuthentication( _('Sorry, but your input is not a valid OpenId')) sreg = getattr(self, 'sreg_attributes', False) if sreg: s = SRegRequest() for k, attr_dic in sreg.items(): if k == "policy_url": s.policy_url = attr_dic continue for attr_name in attr_dic.keys(): s.requestField(field_name=attr_name, required=(k == "required")) auth_request.addExtension(s) ax_schema = getattr(self, 'dataype2ax_schema', False) if ax_schema and request.session.get('force_email_request', True): axr = AXFetchRequest() for data_type, schema in ax_schema.items(): if isinstance(schema, tuple): axr.add(AttrInfo(schema[0], required=True, alias=schema[1])) else: axr.add(AttrInfo(schema, required=True, alias=data_type)) auth_request.addExtension(axr) trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/') return auth_request.redirectURL(trust_root, redirect_to)
def render_GET(self, request): janrain_nonce = request.args.get('janrain_nonce', [None])[0] if janrain_nonce is not None: cookie = request.getCookie('pc_user') if not cookie in globals()['REDIRECTED_USERS']: request.redirect('http://buildpc.ru') return "" consumer = Consumer({}, STORAGE) args = dict((k,unicode(v[0], 'utf-8')) for k,v in request.args.items()) info = consumer.complete(args, RETURN_TO) # Если аутентификация не удалась или отменена # Получение данных пользователя при успешной аутентификации if info.status != SUCCESS: request.redirect('http://buildpc.ru') return "" ax_info = ax.FetchResponse.fromSuccessResponse(info) or ax.FetchResponse() user_data = { 'uid': info.identity_url, 'first_name': ax_info.getSingle(AXINFO['namePerson']), 'last_name': '', } globals()['PASSED_USERS'].update({cookie:user_data}) request.redirect(globals()['REDIRECTED_USERS'].pop(cookie).split('?')[0]\ +'?pr=yandex&code='+cookie) return "" # Далее — выборка существующего или регистрация нового пользователя else: backUrl = request.args.get('backurl', [None])[0] globals()['REDIRECTED_USERS'].update({request.getCookie('pc_user'):backUrl}) # provider = request.get('provider', [None])[0] # url = openid_request.redirectURL(ROOT, ROOT) # Короткие названия для ключей необходимых данных о пользователе. # Список доступных данных см. в разделе Дополнительные данные о пользователе consumer = Consumer({}, STORAGE) openid_request = consumer.begin('http://www.yandex.ru/') # Запрос дополнительной информации о пользователе # Поля, указанные с ключом required, на сайте Яндекса отображаются как обязательные # (незаданные значения подсвечиваются красным цветом) ax_request = ax.FetchRequest() # ax_request.add(ax.AttrInfo(AXINFO['email'], required=True)) # ax_request.add(ax.AttrInfo(AXINFO['nickname'])) ax_request.add(ax.AttrInfo(AXINFO['namePerson'], required=True)) openid_request.addExtension(ax_request) url = openid_request.redirectURL(ROOT, RETURN_TO) request.redirect(url) return ""
def try_login(self, identity_url): """This tries to login with the given identity URL. This function must be called from the login_handler. """ try: consumer = Consumer(session, self.create_store()) auth_request = consumer.begin(identity_url) except discover.DiscoveryFailure: self.signal_error(u'The OpenID was invalid') return redirect(self.get_current_url()) trust_root = request.host_url return redirect( auth_request.redirectURL(request.host_url, self.get_success_url()))
def openid_begin(identifier, return_url, request, max_auth_age=False, sreg=False): """Step one of logging in with OpenID; we resolve a webfinger, if present, then redirect to the provider. Set sreg to True to attempt to retrieve Simple Registration information. Set max_auth_age to a number of seconds to request the OP to ensure that the user authenticated within that many seconds prior to the request, or else force immediate re-authentication.""" session = request.session openid_url = identifier # Does it look like an email address? # If so, try finding an OpenID URL via Webfinger. webfinger_openid = resolve_webfinger(identifier) if webfinger_openid: openid_url = webfinger_openid session['pending_identity_webfinger'] = identifier session.save() cons = Consumer(session=session, store=openid_store) print 1 try: auth_request = cons.begin(openid_url) except DiscoveryFailure: # XXX this error blows raise OpenIDError( "Can't connect to '{0}'. It might not support OpenID.".format(openid_url)) print 2 if sreg: sreg_req = SRegRequest(optional=['nickname', 'email', 'timezone']) auth_request.addExtension(sreg_req) if max_auth_age is not False and max_auth_age >= 0: auth_age_req = PAPERequest(max_auth_age=max_auth_age) auth_request.addExtension(auth_age_req) print 3 # XXX is this realm stuff correct # ^^^ AFAICT, yes, as long as we don't need the assertion to be valid for # sub-domains new_url = auth_request.redirectURL( return_to=return_url, realm=request.host_url, ) print new_url return new_url
def OpenIDStartSubmit(request, default_success_url='/', success_handler=None): response = HttpResponse() openid = request.REQUEST.get('openid_identifier', '').strip() if not openid: return err_page("no_openid_identifier") c = Consumer({}, store.DatastoreStore()) try: auth_request = c.begin(openid) except discover.DiscoveryFailure, e: return err_page("server_discovery", msg='OpenID discovery error with begin on %s: %s' % (openid, str(e)))
def login(request, environ, start_response, ask_info=False): """Redirect the user to the openid provider. Arguments: - ask_info: bool, default False. If set to true, will use the sreg and ax extensions to ask info about the user (email, name...). """ user_url = request.GET['url'] session, oi_session = get_sessions(environ) trust_root = request.host_url return_to = "%s/socialauth/openid/process" % trust_root immediate = False # If set to true and the identity provider can not reply # immediatly (user has to approve), then authentication will fail. # If set to True, then we have to handle the SetupNeeded response case in # process function. consumer = Consumer(oi_session, OPENID_STORE) auth_req = consumer.begin(user_url) if ask_info: sreg_request = sreg.SRegRequest(required=['email' ]) #, optional=SREG_FIELDS) auth_req.addExtension(sreg_request) ax_request = ax.FetchRequest() for alias, url in AX_FIELDS.iteritems(): ax_request.add(ax.AttrInfo(url, alias=alias, required=True)) auth_req.addExtension(ax_request) # PAPE (Provider Authentication Policy Extension): # TODO (an treat pape.Response as well) #pape_request = pape.Request([pape.AUTH_PHISHING_RESISTANT]) #auth_req.addExtension(pape_request) session.save() if auth_req.shouldSendRedirect(): redirect_url = auth_req.redirectURL(trust_root, return_to, immediate=immediate) start_response('302 Redirect', [('Location', redirect_url)]) return [] else: form_html = auth_req.htmlMarkup( trust_root, return_to, form_tag_attrs={'id': 'openid_message'}, immediate=immediate) start_response('200 OK', [('Content-Type', 'text/html')]) return [form_html]
def login(self, req): continue_url = req.values.get('continue') or req.headers.get( 'Referer', '/') consumer = Consumer({}, self.store) authreq = consumer.begin(current_app.config['OPENID2_YADIS']) sregreq = sreg.SRegRequest(optional=['username', 'uid'], required=['email', 'groups']) authreq.addExtension(sregreq) verify_url = urljoin(req.host_url, self.verify_url) + '?' + urlencode( {'continue': continue_url}) urlencode({'continue': continue_url}) url = authreq.redirectURL(return_to=verify_url, realm=req.host_url) return redirect(location=url)
def login(): """ Authenticate a user with Google OpenID. """ # create new session state. should be deleted in login_complete. session['openid_session'] = {} # create consumer and make create request openid_consumer = Consumer(session['openid_session'], FileOpenIDStore('/tmp/')) try: auth_request = openid_consumer.begin(OPENID_ENDPOINT) except DiscoveryFailure, df: return render_template("500.html", error=df)
def getRedirectUrlFor(self, session, openUrlId, returnUrl, realm): store = MemoryStore() session["openId_store"] = store consumer = Consumer(session, store) try: authRequest = consumer.begin(openUrlId) shouldSendRedirect = authRequest.shouldSendRedirect() ##print "should send redirect=%s" % shouldSendRedirect ## see example code for not redirecting??? .../examples/consumer.py #if shouldSendRedirect==False: # html = authRequest.htmlMarkup(realm, returnUrl, \ # form_tag_attrs={"id":"openid_message"}) redirectUrl = authRequest.redirectURL(realm=realm, \ return_to=returnUrl, immediate=False) except Exception, e: return None
def prepare_authentication_request(self, request, redirect_to): if not redirect_to.startswith('http://') or redirect_to.startswith( 'https://'): redirect_to = get_url_host(request) + redirect_to user_url = self.get_user_url(request) if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): raise InvalidAuthentication('i-names are not supported') consumer = Consumer(request.session, OsqaOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: raise InvalidAuthentication( _('Sorry, but your input is not a valid OpenId')) #sreg = getattr(settings, 'OPENID_SREG', False) #if sreg: # s = SRegRequest() # for sarg in sreg: # if sarg.lower().lstrip() == "policy_url": # s.policy_url = sreg[sarg] # else: # for v in sreg[sarg].split(','): # s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required")) # auth_request.addExtension(s) #auth_request.addExtension(SRegRequest(required=['email'])) if request.session.get('force_email_request', True): axr = AXFetchRequest() for data_type, schema in self.dataype2ax_schema.items(): if isinstance(schema, tuple): axr.add(AttrInfo(schema[0], 1, True, schema[1])) else: axr.add(AttrInfo(schema, 1, True, data_type)) auth_request.addExtension(axr) trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/') return auth_request.redirectURL(trust_root, redirect_to)
def clean_openid_url(self): openid_error = self.request.session.get(OPENID_ERROR_SESSION_NAME, '') if openid_error: self.request.session[OPENID_ERROR_SESSION_NAME] = '' raise forms.ValidationError(_(openid_error)) openid_url = self.cleaned_data['openid_url'] #Determine if we need to and can support openid inames disallow_inames = getattr(settings, 'OPENID_DISALLOW_INAMES', False) if disallow_inames and xri.identifierScheme(openid_url) == 'XRI': raise forms.ValidationError(_('i-names are not allowed')) #Set up the openid authorization request consumer = Consumer(self.request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure, df: raise forms.ValidationError("%s: %s" % (_("OpenID Discovery Failure"), df))
def try_login(self, identity_url, ask_for=None, ask_for_optional=None, extensions=None): """This tries to login with the given identity URL. This function must be called from the login_handler. The `ask_for` and `ask_for_optional`parameter can be a set of values to be asked from the openid provider, where keys in `ask_for` are marked as required, and keys in `ask_for_optional` are marked as optional. The following strings can be used in the `ask_for` and `ask_for_optional` parameters: ``aim``, ``blog``, ``country``, ``dob`` (date of birth), ``email``, ``fullname``, ``gender``, ``icq``, ``image``, ``jabber``, ``language``, ``msn``, ``nickname``, ``phone``, ``postcode``, ``skype``, ``timezone``, ``website``, ``yahoo`` `extensions` can be a list of instances of OpenID extension requests that should be passed on with the request. If you use this, please make sure to pass the Response classes of these extensions when initializing OpenID. """ if ask_for and __debug__: for key in ask_for: if key not in ALL_KEYS: raise ValueError('invalid key %r' % key) if ask_for_optional: for key in ask_for_optional: if key not in ALL_KEYS: raise ValueError('invalid optional key %r' % key) try: consumer = Consumer(SessionWrapper(self), self.store_factory()) auth_request = consumer.begin(identity_url) if ask_for or ask_for_optional: self.attach_reg_info(auth_request, ask_for, ask_for_optional) if extensions: for extension in extensions: auth_request.addExtension(extension) except discover.DiscoveryFailure: self.signal_error(u'The OpenID was invalid') return redirect(self.get_current_url()) trust_root = request.host_url return redirect( auth_request.redirectURL(request.host_url, self.get_success_url()))
def ask_openid(self, openid_url, return_url): trust_root = self.get_trust_root() consumer = Consumer(self.request.session, self.store_class()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure: message = _('The OpenID %(url)s was invalid') return self.failure(message % {'url': openid_url}) use_ax, use_sreg = discover_extensions(openid_url) sreg_request = None ax_request = None if use_sreg: sreg_attrs = self.get_sreg_attrs() if 'optional' not in sreg_attrs: sreg_attrs.update({'optional': ['nickname', 'email']}) sreg_request = sreg.SRegRequest(**sreg_attrs) if use_ax: ax_request = ax.FetchRequest() ax_request.add( ax.AttrInfo('http://schema.openid.net/contact/email', alias='email', required=True), ) ax_request.add( ax.AttrInfo('http://schema.openid.net/namePerson/friendly', alias='nickname', required=True), ) ax_attrs = self.get_ax_attrs() for attr in ax_attrs: if len(attr) == 2: ax_request.add(ax.AttrInfo(attr[0], required=attr[1])) else: ax_request.add(ax.AttrInfo(attr[0])) if sreg_request is not None: auth_request.addExtension(sreg_request) if ax_request is not None: auth_request.addExtension(ax_request) redirect_url = auth_request.redirectURL(trust_root, return_url) return redirect(redirect_url)
def begin_openid(session, trust_root, openid_url, resource_redirect_url, redirect_to=None): if not redirect_to: redirect_to = trust_root + '/idpauth/openid_login_complete/' + '?next=' + resource_redirect_url else: redirect_to = trust_root + '/' + redirect_to + '?next=' + resource_redirect_url log.debug(redirect_to) consumer = Consumer(session, DjangoOpenIDStore()) try: auth_request = consumer.begin(openid_url) except DiscoveryFailure: return None auth_request = set_attributes(auth_request) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return redirect_url
def signup(request): "Display the sign-up form and handle registration." word = Words.defaultWordList.pick() state = random.getstate() hexhash = sha(word+settings.SECRET_KEY).hexdigest() openid_failure = '' form = None if request.POST: data = request.POST.copy() # don't validate fields that the user might have filled in before # changing the type.. if data.get('method', 'email') == 'email': data['openid'] = '' else: data['email'] = '' data['password'] = '' data['confirm_password'] = '' oldword = request.session.get('word', '') if oldword: del request.session['word'] form = SignupForm(data, word=oldword) if form.is_valid(): if data.get('method', 'email') == 'email': account = form.save() request.session['account_id'] = account.id account.last_login = datetime.datetime.now() account.save() return HttpResponseRedirect('/feeds/unread/') else: openid = form.get_openid() consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(openid) except DiscoveryFailure: openid_failure = "The OpenID was invalid" else: trust_root = 'http://'+settings.SEYMOUR_DOMAIN + '/' redirect_to = 'http://'+settings.SEYMOUR_DOMAIN+'/signup/openid/' redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url) if not form: initial = {'method': 'email'} form = SignupForm(initial=initial, word=word) request.session['state'] = state request.session['word'] = word request.session[hexhash] = True return render_to_response('accounts/signup.html', { 'hexhash': hexhash, 'form': form, 'openid_failure': openid_failure, 'section': 'signup', 'method': request.POST.get('method', 'email') }, context_instance=RequestContext(request))
def begin(request, confirmed=True, redirect_to=None, on_failure=None, user_url=None, template_name='openid_consumer/signin.html'): on_failure = on_failure or default_on_failure trust_root = getattr(settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/') # foo derbis. redirect_to = redirect_to or getattr( settings, 'OPENID_REDIRECT_TO', # If not explicitly set, assume current URL with complete/ appended get_full_url(request).split('?')[0] + 'complete/') # In case they were lazy... if not redirect_to.startswith('http://') or redirect_to.startswith( 'https://'): redirect_to = get_url_host(request) + redirect_to if request.GET.get('next') and is_valid_next_url(request.GET['next']): if '?' in redirect_to: join = '&' else: join = '?' redirect_to += join + urlencode({'next': request.GET['next']}) if not user_url: user_url = request.REQUEST.get('openid_url', None) if not user_url: request_path = request.path if request.GET.get('next'): request_path += '?' + urlencode({'next': request.GET['next']}) return render(template_name, { 'action': request_path, }, RequestContext(request)) if xri.identifierScheme(user_url) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): return on_failure(request, _('i-names are not supported')) consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(user_url) except DiscoveryFailure: return on_failure(request, _('The OpenID was invalid')) sreg = getattr(settings, 'OPENID_SREG', False) if sreg: s = SRegRequest() for sarg in sreg: if sarg.lower().lstrip() == "policy_url": s.policy_url = sreg[sarg] else: for v in sreg[sarg].split(','): s.requestField( field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required")) auth_request.addExtension(s) pape = getattr(settings, 'OPENID_PAPE', False) if pape: if openid.__version__ <= '2.0.0' and openid.__version__ >= '2.1.0': raise ImportError, 'For pape extension you need python-openid 2.1.0 or newer' p = PapeRequest() for parg in pape: if parg.lower().strip() == 'policy_list': for v in pape[parg].split(','): p.addPolicyURI(v) elif parg.lower().strip() == 'max_auth_age': p.max_auth_age = pape[parg] auth_request.addExtension(p) ax = getattr(settings, 'OPENID_AX', []) if ax: axr = AXFetchRequest() for i in ax: axr.add( AttrInfo(i['type_uri'], i['count'], i['required'], i['alias'])) auth_request.addExtension(axr) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url)
def OpenIDStartSubmit(request, default_success_url='/'): response = django.http.HttpResponse() if request.method == 'POST': openid = request.POST.get('openid_identifier', '') openid = openid.strip() if not openid: return show_main_page(request) c = Consumer({},get_store()) try: auth_request = c.begin(openid) except discover.DiscoveryFailure, e: logging.error('OpenID discovery error with begin on %s: %s' % (openid, str(e))) return show_main_page(request, 'An error occured determining your server information. Please try again.') from openid.extensions import sreg sreg_request = sreg.SRegRequest( optional=['dob', 'gender', 'postcode'], required=['email', 'nickname', 'fullname', 'country', 'language', 'timezone']) auth_request.addExtension(sreg_request) from openid.extensions import ax ax_req = ax.FetchRequest() ax_req.add(ax.AttrInfo('http://schema.openid.net/contact/email', alias='email',required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/first', alias='firstname',required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/last', alias='lastname',required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/pref/language', alias='language',required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/contact/country/home', alias='country',required=True)) auth_request.addExtension(ax_req) import urlparse parts = list(urlparse.urlparse(get_full_path(request))) # finish URL with the leading "/" character removed parts[2] = django.core.urlresolvers.reverse('openidgae.views.OpenIDFinish')[1:] continueUrl = get_continue_url(request, default_success_url) import urllib parts[4] = 'continue=%s' % urllib.quote_plus(continueUrl) parts[5] = '' return_to = urlparse.urlunparse(parts) realm = urlparse.urlunparse(parts[0:2] + [''] * 4) # save the session stuff session = openidgae.get_session(request, response) import pickle session.openid_stuff = pickle.dumps(c.session) session.put() # send the redirect! we use a meta because appengine bombs out # sometimes with long redirect urls redirect_url = auth_request.redirectURL(realm, return_to) response.write( "<html><head><meta http-equiv=\"refresh\" content=\"0;url=%s\"></head><body></body></html>" % (redirect_url,)) return response
def signin(request, sreg=None, extension_args={}, on_failure=default_on_failure): openid_url = None if is_valid_next_url(request.GET.get('next')): next = request.GET['next'] elif is_valid_next_url( get_address(request.META.get('HTTP_REFERER'), request)): next = get_address(request.META['HTTP_REFERER'], request) else: next = getattr(settings, 'OPENID_REDIRECT_NEXT', '/') def get_with_next(url, next): if next: return '%s?%s' % (url, urlencode({'next': next})) else: return url if request.user.is_authenticated() and 'force' not in request.GET: return HttpResponseRedirect(next) request_path = get_with_next(request.path, next) if request.method == 'POST': form = OpenidSigninForm(request.POST, auto_id='id_%s') if form.is_valid(): # first remove email and nickname from sreg if the are in to prevent dup extension_args['sreg.optional'] = 'email,nickname' if sreg: sreg = ','.join([ arg for arg in sreg.split(',') if arg not in extension_args['sreg.optional'] ]) extension_args['sreg.optional'] += ',' + sreg trust_root = getattr(settings, 'OPENID_TRUST_ROOT', request.build_absolute_uri('/')) redirect_to = get_with_next( request.build_absolute_uri(reverse('openid_complete')), next) if xri.identifierScheme( form.cleaned_data['openid_url']) == 'XRI' and getattr( settings, 'OPENID_DISALLOW_INAMES', False): return on_failure(request, _("i-names are not supported")) consumer = Consumer(request.session, DjangoOpenIDStore()) try: auth_request = consumer.begin(form.cleaned_data['openid_url']) except DiscoveryFailure: return on_failure(request, _("The OpenID was invalid")) # Add extension args (for things like simple registration) for name, value in extension_args.items(): namespace, key = name.split('.', 1) auth_request.addExtensionArg(namespace, key, value) redirect_url = auth_request.redirectURL(trust_root, redirect_to) return HttpResponseRedirect(redirect_url) else: form = OpenidSigninForm(auto_id='id_%s') return { 'form': form, 'action': request_path, }