本文整理汇总了Python中openid.extensions.sreg.SRegResponse类的典型用法代码示例。如果您正苦于以下问题:Python SRegResponse类的具体用法?Python SRegResponse怎么用?Python SRegResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SRegResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Respond
def Respond(self, oidresponse, sreg_req=False):
"""Send an OpenID response.
Args:
oidresponse: OpenIDResponse
The response to send, usually created by OpenIDRequest.answer().
"""
logging.warning('Respond: oidresponse.request.mode ' + oidresponse.request.mode)
if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']:
if sreg_req:
sreg_resp = SRegResponse.extractResponse(sreg_req, {'email': self.user, 'nickname': self.user.rsplit('@',1)[0]})
oidresponse.addExtension(sreg_resp)
logging.debug('Using response: %s' % oidresponse)
encoded_response = oidserver.encodeResponse(oidresponse)
# update() would be nice, but wsgiref.headers.Headers doesn't implement it
for header, value in encoded_response.headers.items():
self.response.headers[header] = str(value)
if encoded_response.code in (301, 302):
self.redirect(self.response.headers['location'])
else:
self.response.set_status(encoded_response.code)
if encoded_response.body:
logging.debug('Sending response body: %s' % encoded_response.body)
self.response.out.write(encoded_response.body)
else:
self.response.out.write('')
示例2: Respond
def Respond(self, oidresponse):
logging.warning('Respond: oidresponse.request.mode ' + oidresponse.request.mode)
if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']:
user = users.get_current_user()
if user:
from openid.extensions.sreg import SRegRequest, SRegResponse
sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request)
if sreg_req.wereFieldsRequested():
logging.info("sreg_req:%s", sreg_req.allRequestedFields())
user_data = {'nickname':user.nickname(),
'email':user.email()}
sreg_resp = SRegResponse.extractResponse(sreg_req, user_data)
sreg_resp.toMessage(oidresponse.fields)
logging.info('Using response: %s' % oidresponse)
encoded_response = oidserver.encodeResponse(oidresponse)
for header, value in encoded_response.headers.items():
self.response.headers[header] = str(value)
if encoded_response.code in (301, 302):
self.redirect(self.response.headers['location'])
else:
self.response.set_status(encoded_response.code)
if encoded_response.body:
logging.debug('Sending response body: %s' % encoded_response.body)
self.response.out.write(encoded_response.body)
else:
self.response.out.write('')
示例3: createPositiveResponse
def createPositiveResponse(self):
"""Create a positive assertion OpenIDResponse.
This method should be called to create the response to
successful checkid requests.
If the trust root for the request is in openid_sreg_trustroots,
then additional user information is included with the
response.
"""
assert self.account is not None, (
'Must be logged in for positive OpenID response')
assert self.openid_request is not None, (
'No OpenID request to respond to.')
if not self.isIdentityOwner():
return self.createFailedResponse()
if self.openid_request.idSelect():
response = self.openid_request.answer(
True, identity=self.user_identity_url)
else:
response = self.openid_request.answer(True)
person = IPerson(self.account)
sreg_fields = dict(
nickname=person.name,
email=person.preferredemail.email,
fullname=self.account.displayname)
sreg_request = SRegRequest.fromOpenIDRequest(self.openid_request)
sreg_response = SRegResponse.extractResponse(
sreg_request, sreg_fields)
response.addExtension(sreg_response)
return response
示例4: _parse_response
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
示例5: test_login_create_users
def test_login_create_users(self):
settings.OPENID_CREATE_USERS = True
# Create a user with the same name as we'll pass back via sreg.
User.objects.create_user('someuser', '[email protected]')
# Posting in an identity URL begins the authentication request:
response = self.client.post('/openid/login/',
{'openid_identifier': 'http://example.com/identity',
'next': '/getuser/'})
self.assertContains(response, 'OpenID transaction in progress')
# Complete the request, passing back some simple registration
# data. The user is redirected to the next URL.
openid_request = self.provider.parseFormPost(response.content)
sreg_request = SRegRequest.fromOpenIDRequest(openid_request)
openid_response = openid_request.answer(True)
sreg_response = SRegResponse.extractResponse(
sreg_request, {'nickname': 'someuser', 'fullname': 'Some User',
'email': '[email protected]'})
openid_response.addExtension(sreg_response)
response = self.complete(openid_response)
self.assertRedirects(response, 'http://testserver/getuser/')
# And they are now logged in as a new user (they haven't taken
# over the existing "someuser" user).
response = self.client.get('/getuser/')
self.assertEquals(response.content, 'someuser2')
# Check the details of the new user.
user = User.objects.get(username='someuser2')
self.assertEquals(user.first_name, 'Some')
self.assertEquals(user.last_name, 'User')
self.assertEquals(user.email, '[email protected]')
示例6: test_known_trust_roots_with_auto_authorize
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)])
示例7: authenticateCredentials
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
示例8: test_required_fields_checked
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'))
示例9: login_complete
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'))
示例10: handle_sreg
def handle_sreg(request, response):
"""Handle any sreg data requests"""
sreg_req = SRegRequest.fromOpenIDRequest(request)
# Extract information if required
if sreg_req.wereFieldsRequested():
fields = config.sreg_fields()
if not fields:
return
sreg_resp = SRegResponse.extractResponse(sreg_req, config.sreg_fields())
sreg_resp.toMessage(response.fields)
示例11: __init__
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)
示例12: from_openid_response
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
示例13: sreg
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
示例14: Respond
def Respond(self, oidresponse):
"""Send an OpenID response.
Args:
oidresponse: OpenIDResponse
The response to send, usually created by OpenIDRequest.answer().
"""
logging.warning('Respond: oidresponse.request.mode ' + oidresponse.request.mode)
if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']:
# user = users.get_current_user()
user = self.get_current_user()
if user:
from openid.extensions.sreg import SRegRequest,SRegResponse
sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request)
logging.info("sreg_req:%s",sreg_req.allRequestedFields())
if sreg_req.wereFieldsRequested():
user_data = {'nickname':user.nickname,
'email':user.email}
sreg_resp = SRegResponse.extractResponse(sreg_req, user_data)
sreg_resp.toMessage(oidresponse.fields)
# add nickname, using the Simple Registration Extension:
# http://www.openidenabled.com/openid/simple-registration-extension/
#oidresponse.fields.setArg('http://openid.net/sreg/1.0', 'nickname', user.nickname)
#oidresponse.fields.setArg('http://openid.net/sreg/1.0', 'email', user.email)
#oidresponse.fields.setArg('http://openid.net/srv/ax/1.0', 'nickname', user.nickname)
#oidresponse.fields.setArg('http://openid.net/srv/ax/1.0', 'email', user.email)
from openid.extensions.ax import FetchRequest, FetchResponse
res ={'nickname':user.nickname,'email':user.email,'attr0':user.email,'attr1':user.nickname}
ax_req = FetchRequest.fromOpenIDRequest(oidresponse.request)
logging.info("ax_req:%s",ax_req.getRequiredAttrs())
ax_res = FetchResponse()
for x in ax_req.iterAttrs():
ax_res.addValue(x.type_uri,res[x.alias] )
ax_res.toMessage(oidresponse.fields)
pass
logging.info('Using response: %s' % oidresponse)
encoded_response = oidserver.encodeResponse(oidresponse)
# update() would be nice, but wsgiref.headers.Headers doesn't implement it
for header, value in encoded_response.headers.items():
self.response.headers[header] = str(value)
if encoded_response.code in (301, 302):
self.redirect(self.response.headers['location'])
else:
self.response.set_status(encoded_response.code)
if encoded_response.body:
logging.debug('Sending response body: %s' % encoded_response.body)
self.response.out.write(encoded_response.body)
else:
self.response.out.write('')
示例15: openid_end
def openid_end(return_url, request):
"""Step two of logging in; the OpenID provider redirects back here."""
cons = Consumer(session=request.session, store=openid_store)
params = request.params
if 'return_key' in params and not key_from_request(request):
# We've followed a return_key that has terminated at the OpenID request
# i.e. this is a stashed OpenID request (or a bogus return_key); the
# OpenID request will therefore NOT have the return_key in its
# return_to URL, so strip it
log.debug("OpenID check stripping stale or bogus return_key(s) '{0}'"
.format(params.getall('return_key')))
# Janrain OpenID treats params as a normal dict, so it's safe to lose
# the MultiDict here (AFAICT).
params = dict((k, v) for k, v in params.iteritems() if k != 'return_key')
res = cons.complete(params, return_url)
if res.status == SUCCESS:
pass
elif res.status == FAILURE:
# The errors are, very helpfully, plain strings. Nevermind that
# there's a little hierarchy of exception classes inside the openid
# library; they all get squashed into homogenous goo in the return
# value. Fucking awesome. Check for a few common things here and
# assume the rest are wacky internal errors
log.error('openid failure: ' + res.message)
if res.message == 'Nonce already used or out of range':
# You tend to get this if you hit refresh on login_finish
raise OpenIDError("Sorry! Your login attempt expired; please start over.")
else:
raise OpenIDError("Something has gone hilariously wrong.")
elif res.status == CANCEL:
raise OpenIDError("Looks like you canceled the login.")
else:
log.error("Unexpected OpenID return status '{0}' with message '{1}'"
.format(res.status, res.message))
raise OpenIDError("Something has gone hilariously wrong.")
identity_url = unicode(res.identity_url)
identity_webfinger = request.session.pop('pending_identity_webfinger', None)
sreg_res = SRegResponse.fromSuccessResponse(res) or dict()
pape_res = PAPEResponse.fromSuccessResponse(res)
auth_time = pape_res.auth_time
return identity_url, identity_webfinger, auth_time, sreg_res