本文整理汇总了Python中openid.consumer.consumer.Consumer类的典型用法代码示例。如果您正苦于以下问题:Python Consumer类的具体用法?Python Consumer怎么用?Python Consumer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Consumer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
def get(self):
federated_id = self.request.args.get(AUTH_REQUEST_FIELD)
if not federated_id:
response = Response("missing %s field\n" % AUTH_REQUEST_FIELD)
# Since we only care about Ajax requests we don't have to do
# anything more informative than a 409.
response.status_code = 409
return self.respond(response)
session = self.environ.get(BEAKER_ENV_KEY)
try:
auth_request = Consumer(session, aeoid_store.AppEngineStore()).begin(federated_id)
except DiscoveryFailure:
response = Response("discovery failure\n")
# Since we only care about Ajax requests we don't have to do
# anything more informative than a 409.
response.status_code = 409
return self.respond(response)
# If this raises a different exception it will be caught by the fwerks dispatcher.
# TODO: We need a nicer way of handling exceptions here.
host_url = self.request.host_url
cont = self.request.args.get("continuation", "/")
return_to = urlparse.urljoin(host_url, cont)
redirect_url = auth_request.redirectURL(host_url, return_to)
# The Ajax request wants the redirect url as plain text, not an actual
# HTTP redirect.
response = self.respond(Response(redirect_url))
session.save()
return response
示例2: try_login
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()))
示例3: openid2_get_redirect
def openid2_get_redirect(request, provider, callback, scope, mode):
xrds = urllib.urlopen(providers[provider]["xrds"])
if xrds.getcode() != 200:
raise Exception("OpenID Failed: Invalid response from " + providers[provider]["displayname"] + " on obtaining a XRDS information: " + xrds.read())
xrds = xrds.read()
from openid.consumer.consumer import Consumer
from openid.consumer.discover import OpenIDServiceEndpoint
from openid.store.memstore import MemoryStore
service = OpenIDServiceEndpoint.fromXRDS(providers[provider]["xrds"], xrds)[0]
consumer = Consumer(request.session, MemoryStore())
auth = consumer.beginWithoutDiscovery(service)
if "extensions" in providers[provider]:
for ext, d in providers[provider]["extensions"].iteritems():
for k, v in d.iteritems():
auth.addExtensionArg(ext, k, v)
if mode == "compact": # works with Google
auth.addExtensionArg("http://specs.openid.net/extensions/ui/1.0", "mode", "popup")
return auth.redirectURL(realm=SITE_ROOT_URL, return_to=callback)
示例4: ask_openid
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)
示例5: complete
def complete(request, on_success=None, on_failure=None, failure_template='openid_consumer/failure.html'):
on_success = on_success or default_on_success
on_failure = on_failure or default_on_failure
consumer = Consumer(request.session, DjangoOpenIDStore())
#dummydebug
#for r in request.GET.items():
# print r
# JanRain library raises a warning if passed unicode objects as the keys,
# so we convert to bytestrings before passing to the library
query_dict = dict([
(k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items()
])
url = get_url_host(request) + request.path
openid_response = consumer.complete(query_dict, url)
if openid_response.status == SUCCESS:
return on_success(request, openid_response.identity_url, openid_response)
elif openid_response.status == CANCEL:
return on_failure(request, _('The request was cancelled'), failure_template)
elif openid_response.status == FAILURE:
return on_failure(request, openid_response.message, failure_template)
elif openid_response.status == SETUP_NEEDED:
return on_failure(request, _('Setup needed'), failure_template)
else:
assert False, "Bad openid status: %s" % openid_response.status
示例6: complete
def complete(request, on_success=None, on_failure=None, return_to=None):
""" complete openid signin """
on_success = on_success or default_on_success
on_failure = on_failure or default_on_failure
logging.debug('in django_authopenid.complete')
consumer = Consumer(request.session, DjangoOpenIDStore())
# make sure params are encoded in utf8
params = dict((k,smart_unicode(v)) for k, v in request.GET.items())
openid_response = consumer.complete(params, return_to)
if openid_response.status == SUCCESS:
logging.debug('SUCCESS')
return on_success(request, openid_response.identity_url,
openid_response)
elif openid_response.status == CANCEL:
logging.debug('CANCEL')
return on_failure(request, 'The request was canceled')
elif openid_response.status == FAILURE:
logging.debug('FAILURE')
return on_failure(request, openid_response.message)
elif openid_response.status == SETUP_NEEDED:
logging.debug('SETUP NEEDED')
return on_failure(request, 'Setup needed')
else:
logging.debug('BAD OPENID STATUS')
assert False, "Bad openid status: %s" % openid_response.status
示例7: ask_openid
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)
示例8: callback
def callback(request):
consumer = Consumer(request.session, FileOpenIDStore('/tmp/gtugdemo'))
openid_response = consumer.complete(request.REQUEST, 'http://%s/login/callback' % request.get_host())
if openid_response.status == SUCCESS:
print "SUCCESS"
ax_response = ax.FetchResponse.fromSuccessResponse(openid_response)
if ax_response:
ax_items = {
'firstname': ax_response.get(
'http://axschema.org/namePerson/first'),
'lastname': ax_response.get(
'http://axschema.org/namePerson/last'),
'email': ax_response.get(
'http://axschema.org/contact/email'),
}
username = ''.join(ax_items['email'])
firstname = ''.join(ax_items['firstname'])
lastname = ''.join(ax_items['lastname'])
email = ''.join(ax_items['email'])
register_user(username, firstname , lastname , email)
print "%s %s %s" % (firstname, lastname, email)
user = User.objects.get(username=username)
user.backend='django.contrib.auth.backends.ModelBackend'
login(request, user)
return redirect(to='http://%s/' % request.get_host())
if openid_response.status == FAILURE:
print "NOOOOOOOOOOO: %s" % openid_response.message
return render_to_response('login.html', locals(), context_instance=RequestContext(request))
示例9: libopenid
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)
示例10: libopenid
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)
示例11: callback
def callback(request):
consumer = Consumer(request.session, FileOpenIDStore("/tmp/gtugdemo"))
openid_response = consumer.complete(request.REQUEST, "http://%s/login/callback" % request.get_host())
if openid_response.status == SUCCESS:
ax_response = ax.FetchResponse.fromSuccessResponse(openid_response)
if ax_response:
ax_items = {
"firstname": ax_response.get("http://axschema.org/namePerson/first"),
"lastname": ax_response.get("http://axschema.org/namePerson/last"),
"email": ax_response.get("http://schema.openid.net/contact/email"),
}
username = "".join(ax_items["email"])
firstname = "".join(ax_items["firstname"])
lastname = "".join(ax_items["lastname"])
email = "".join(ax_items["email"])
register_user(username, firstname, lastname, email)
user = User.objects.get(username=username)
user.backend = "django.contrib.auth.backends.ModelBackend"
login(request, user)
return redirect(to="http://%s/" % request.get_host())
else:
message = openid_response.message
return render_to_response("login.html", locals(), context_instance=RequestContext(request))
示例12: login
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)))
示例13: __call__
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
示例14: begin_openid
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)
示例15: get_auth_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())