def test_112(self): args = {'openid.assoc_handle': 'fa1f5ff0-cde4-11dc-a183-3714bfd55ca8', 'openid.claimed_id': 'http://binkley.lan/user/test01', 'openid.identity': 'http://test01.binkley.lan/', 'openid.mode': 'id_res', 'openid.ns': 'http://specs.openid.net/auth/2.0', 'openid.ns.pape': 'http://specs.openid.net/extensions/pape/1.0', 'openid.op_endpoint': 'http://binkley.lan/server', 'openid.pape.auth_policies': 'none', 'openid.pape.auth_time': '2008-01-28T20:42:36Z', 'openid.pape.nist_auth_level': '0', 'openid.response_nonce': '2008-01-28T21:07:04Z99Q=', 'openid.return_to': 'http://binkley.lan:8001/process?janrain_nonce=2008-01-28T21%3A07%3A02Z0tMIKx', 'openid.sig': 'YJlWH4U6SroB1HoPkmEKx9AyGGg=', 'openid.signed': 'assoc_handle,identity,response_nonce,return_to,claimed_id,op_endpoint,pape.auth_time,ns.pape,pape.nist_auth_level,pape.auth_policies' } self.failUnlessEqual(OPENID2_NS, args['openid.ns']) incoming = Message.fromPostArgs(args) self.failUnless(incoming.isOpenID2()) car = self.consumer._createCheckAuthRequest(incoming) expected_args = args.copy() expected_args['openid.mode'] = 'check_authentication' expected =Message.fromPostArgs(expected_args) self.failUnless(expected.isOpenID2()) self.failUnlessEqual(expected, car) self.failUnlessEqual(expected_args, car.toPostArgs())
def test_idResMissingField(self): # XXX - this test is passing, but not necessarily by what it # is supposed to test for. status in FAILURE, but it's because # *check_auth* failed, not because it's missing an arg, exactly. message = Message.fromPostArgs({'openid.mode': 'id_res'}) self.failUnlessRaises(ProtocolError, self.consumer._doIdRes, message, self.endpoint, None)
def test_112B(self): args = { 'openid.assoc_handle': 'fa1f5ff0-cde4-11dc-a183-3714bfd55ca8', 'openid.claimed_id': 'http://binkley.lan/user/test01', 'openid.identity': 'http://test01.binkley.lan/', 'openid.mode': 'id_res', 'openid.ns': 'http://specs.openid.net/auth/2.0', 'openid.ns.pape': 'http://specs.openid.net/extensions/pape/1.0', 'openid.op_endpoint': 'http://binkley.lan/server', 'openid.pape.auth_policies': 'none', 'openid.pape.auth_time': '2008-01-28T20:42:36Z', 'openid.pape.nist_auth_level': '0', 'openid.response_nonce': '2008-01-28T21:07:04Z99Q=', 'openid.return_to': 'http://binkley.lan:8001/process?janrain_nonce=2008-01-28T21%3A07%3A02Z0tMIKx', 'openid.sig': 'YJlWH4U6SroB1HoPkmEKx9AyGGg=', 'openid.signed': 'assoc_handle,identity,response_nonce,return_to,claimed_id,op_endpoint,pape.auth_time,' 'ns.pape,pape.nist_auth_level,pape.auth_policies'} m = Message.fromPostArgs(args) missing = [] for k in args['openid.signed'].split(','): if not ("openid." + k) in m.toPostArgs().keys(): missing.append(k) self.assertEqual(missing, [], missing) self.assertEqual(m.toPostArgs(), args) self.assertTrue(m.isOpenID2())
def test_bad_args(self): query = { 'openid.signed':'foo', 'closid.foo':'something', } consumer = BadArgCheckingConsumer(self.store) consumer._checkAuth(Message.fromPostArgs(query), 'does://not.matter')
def test_idResURLMismatch(self): class VerifiedError(Exception): pass def discoverAndVerify(claimed_id, _to_match_endpoints): raise VerifiedError self.consumer._discoverAndVerify = discoverAndVerify self.disableReturnToChecking() message = Message.fromPostArgs( {'openid.mode': 'id_res', 'openid.return_to': 'return_to (just anything)', 'openid.identity': 'something wrong (not self.consumer_id)', 'openid.assoc_handle': 'does not matter', 'openid.sig': GOODSIG, 'openid.signed': 'identity,return_to', }) self.consumer.store = GoodAssocStore() self.failUnlessRaises(VerifiedError, self.consumer.complete, message, self.endpoint) self.failUnlessLogMatches('Error attempting to use stored', 'Attempting discovery')
def test_setupNeededOpenID1(self): """The minimum conditions necessary to trigger Setup Needed""" setup_url = 'http://unittest/setup-here' message = Message.fromPostArgs({ 'openid.mode': 'id_res', 'openid.user_setup_url': setup_url, }) self.failUnless(message.isOpenID1()) self.failUnlessSetupNeeded(setup_url, message)
def test_error(self): self.fetcher.response = HTTPResponse( "http://some_url", 404, {'Hea': 'der'}, 'blah:blah\n') query = {'openid.signed': 'stuff', 'openid.stuff':'a value'} r = self.consumer._checkAuth(Message.fromPostArgs(query), http_server_url) self.failIf(r) self.failUnless(self.messages)
def test_error_404(self): """404 from a kv post raises HTTPFetchingError""" self.fetcher.response = HTTPResponse( "http://some_url", 404, {'Hea': 'der'}, 'blah:blah\n') self.failUnlessRaises( fetchers.HTTPFetchingError, self.consumer._makeKVPost, Message.fromPostArgs({'mode':'associate'}), "http://server_url")
def post(self): parsed = urlparse.urlparse(self.request.uri) request_url_without_path = parsed[0] + '://' + parsed[1] request_url_without_params = request_url_without_path + parsed[2] token = self.request.get('token') or urlparse.urlparse(self.request.uri)[2].rsplit('/',2)[2] oid_args = False query = datastore.Query('Verification') query['token ='] = token v = query.Get(1) if v: v = v[0] if v['expires'] > time.time(): self.user = v['email'] self.oid_args = pickle.loads(str(v['oidrequest'])) else: error = 'That token has expired. Please try again.' datastore.Delete(v) else: error = 'No such token found.' if not self.CheckUser(): self.ShowFrontPage(error) return args = self.ArgsToDict() try: oidrequest = OpenIDServer.CheckIDRequest.fromMessage(OpenIDMessage.fromPostArgs(args), '') except: trace = ''.join(traceback.format_exception(*sys.exc_info())) self.ReportError('Error decoding login request:\n%s' % trace) return if True: #args.has_key('yes'): logging.debug('Confirming identity to %s' % oidrequest.trust_root) if args.get('remember', '') == 'yes': logging.info('Setting cookie to remember openid login for two weeks') expires = datetime.datetime.now() + datetime.timedelta(weeks=2) expires_rfc822 = expires.strftime('%a, %d %b %Y %H:%M:%S +0000') self.response.headers.add_header( 'Set-Cookie', 'openid_remembered=yes; expires=%s' % expires_rfc822) self.store_login(oidrequest, 'confirmed') sreg_req = SRegRequest.fromOpenIDRequest(oidrequest) self.Respond(oidrequest.answer(True, request_url_without_path + '/id/' + urllib.quote(self.user)), sreg_req) elif args.has_key('no'): logging.debug('Login denied, sending cancel to %s' % oidrequest.trust_root) self.store_login(oidrequest, 'declined') return self.Respond(oidrequest.answer(False)) else: self.ReportError('Bad login request.')
def test_setupNeededOpenID1_extra(self): """Extra stuff along with setup_url still trigger Setup Needed""" setup_url = 'http://unittest/setup-here' message = Message.fromPostArgs({ 'openid.mode': 'id_res', 'openid.user_setup_url': setup_url, 'openid.identity': 'bogus', }) self.failUnless(message.isOpenID1()) self.failUnlessSetupNeeded(setup_url, message)
def test_notAList(self): # XXX: should be a Message object test, not a consumer test # Value should be a single string. If it's a list, it should generate # an exception. query = {'openid.mode': ['cancel']} try: r = Message.fromPostArgs(query) except TypeError, err: self.failUnless(str(err).find('values') != -1, err)
def test_error(self): msg = 'an error message' message = Message.fromPostArgs({'openid.mode': 'error', 'openid.error': msg, }) self.disableReturnToChecking() r = self.consumer.complete(message, self.endpoint) self.failUnlessEqual(r.status, FAILURE) self.failUnless(r.identity_url == self.endpoint.claimed_id) self.failUnlessEqual(r.message, msg)
def test_overrideMethod(self): """Be sure that caller cannot change form method to GET.""" m = Message.fromPostArgs(self.postargs) tag_attrs = dict(self.form_tag_attrs) tag_attrs['method'] = 'GET' html = m.toFormMarkup(self.action_url, self.form_tag_attrs, self.submit_text) self._checkForm(html, m, self.action_url, self.form_tag_attrs, self.submit_text)
def post(self): logging.debug('FinishLogin') args = self.arg_map(self.request) try: from openid.message import Message message = Message.fromPostArgs(args) oidrequest = OpenIDServer.CheckIDRequest.fromMessage( message, oidserver.op_endpoint) self.verify_request(oidrequest, self.request) except OpenIDServer.ProtocolError, exc: self.render_response(exc) return
def test_error_exception_unwrapped(self): """Ensure that exceptions are bubbled through from fetchers when making associations """ self.fetcher = ExceptionRaisingMockFetcher() fetchers.setDefaultFetcher(self.fetcher, wrap_exceptions=False) self.failUnlessRaises(self.fetcher.MyException, self.consumer._makeKVPost, Message.fromPostArgs({'mode':'associate'}), "http://server_url") # exception fetching returns no association e = OpenIDServiceEndpoint() e.server_url = 'some://url' self.failUnlessRaises(self.fetcher.MyException, self.consumer._getAssociation, e) self.failUnlessRaises(self.fetcher.MyException, self.consumer._checkAuth, Message.fromPostArgs({'openid.signed':''}), 'some://url')
def test_overrideRequired(self): """Be sure that caller CANNOT change the form charset for encoding type.""" m = Message.fromPostArgs(self.postargs) tag_attrs = dict(self.form_tag_attrs) tag_attrs['accept-charset'] = 'UCS4' tag_attrs['enctype'] = 'invalid/x-broken' html = m.toFormMarkup(self.action_url, tag_attrs, self.submit_text) self._checkForm(html, m, self.action_url, tag_attrs, self.submit_text)
def test_errorWithOptionalKeys(self): msg = 'an error message' contact = 'me' reference = 'support ticket' message = Message.fromPostArgs({'openid.mode': 'error', 'openid.error': msg, 'openid.reference': reference, 'openid.contact': contact, 'openid.ns': OPENID2_NS, }) r = self.consumer.complete(message, self.endpoint, None) self.failUnlessEqual(r.status, FAILURE) self.failUnless(r.identity_url == self.endpoint.claimed_id) self.failUnless(r.contact == contact) self.failUnless(r.reference == reference) self.failUnlessEqual(r.message, msg)
def setUp(self): self.factory = RequestFactory() self.request = self.factory.get(path=reverse('idPage')) # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.identity': reverse('idPage'), 'openid.return_to': 'http://127.0.0.1/%s' % (self.id(),), 'openid.sreg.required': 'postcode', }) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request)
def test_errorWithNoOptionalKeys(self): msg = 'an error message' contact = 'some contact info here' message = Message.fromPostArgs({'openid.mode': 'error', 'openid.error': msg, 'openid.contact': contact, }) self.disableReturnToChecking() r = self.consumer.complete(message, self.endpoint) self.failUnlessEqual(r.status, FAILURE) self.failUnless(r.identity_url == self.endpoint.claimed_id) self.failUnless(r.contact == contact) self.failUnless(r.reference is None) self.failUnlessEqual(r.message, msg)
def setUp(self): TestIdRes.setUp(self) self.assoc = GoodAssociation() self.assoc.handle = "{not_dumb}" self.store.storeAssociation(self.endpoint.server_url, self.assoc) self.message = Message.fromPostArgs({ 'openid.mode': 'id_res', 'openid.identity': '=example', 'openid.sig': GOODSIG, 'openid.assoc_handle': self.assoc.handle, 'openid.signed': 'mode,identity,assoc_handle,signed', 'frobboz': 'banzit', })
def dummyOidRequest(request, id, id_url, return_url = None): """Build an openid_request with id_url """ # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' if return_url == None: return_url = 'http://127.0.0.1/%s' % (id,) message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.claimed_id': '', 'openid.identity': id_url, 'openid.return_to': return_url, 'openid.sreg.required': 'postcode', }) return CheckIDRequest.fromMessage(message, op_endpoint)
def setUp(self): self.request = dummyRequest() id_url = util.getViewURL(self.request, views.idPage) # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.identity': id_url, 'openid.return_to': 'http://127.0.0.1/%s' % (self.id(),), 'openid.sreg.required': 'postcode', }) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request)
def test_checkAuthTriggered(self): message = Message.fromPostArgs({ 'openid.return_to':self.return_to, 'openid.identity':self.server_id, 'openid.assoc_handle':'not_found', 'openid.sig': GOODSIG, 'openid.signed': 'identity,return_to', }) self.disableReturnToChecking() try: result = self.consumer._doIdRes(message, self.endpoint, None) except CheckAuthHappened: pass else: self.fail('_checkAuth did not happen. Result was: %r %s' % (result, self.messages))
def setUp(self): self.request = dummyRequest() id_url = urljoin('http://example.cz/', reverse('server:local_id')) # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.identity': id_url, 'openid.return_to': 'http://127.0.0.1/%s' % (self.id(),), 'openid.sreg.required': 'postcode', }) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request)
def test_fromPostArgs_ns11(self): # An example of the stuff that some Drupal installations send us, # which includes openid.ns but is 1.1. query = { 'openid.assoc_handle': '', 'openid.claimed_id': 'http://foobar.invalid/', 'openid.identity': 'http://foobar.myopenid.com', 'openid.mode': 'checkid_setup', 'openid.ns': 'http://openid.net/signon/1.1', 'openid.ns.sreg': 'http://openid.net/extensions/sreg/1.1', 'openid.return_to': 'http://drupal.invalid/return_to', 'openid.sreg.required': 'nickname,email', 'openid.trust_root': 'http://drupal.invalid', } m = Message.fromPostArgs(query) self.assertTrue(m.isOpenID1())
def setUp(self): self.request = dummyRequest() id_url = util.getViewURL(self.request, 'profile_view', args=('normal',)) # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.identity': id_url, 'openid.return_to': 'http://127.0.0.1/%s' % (self.id(),), }) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) server_util.authorizeOpenId(self.request, User.objects.get( username='******')) views.setRequest(self.request, self.openid_request)
def setUp(self): self.request = dummyRequest() id_url = util.get_view_url(self.request, views.idPage) # Set up the OpenID request we're responding to. op_endpoint = "http://127.0.0.1:8080/endpoint" message = Message.fromPostArgs( { "openid.mode": "checkid_setup", "openid.identity": id_url, "openid.return_to": "http://127.0.0.1/%s" % (self.id(),), "openid.sreg.required": "postcode", } ) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.set_request(self.request, self.openid_request)
def test_toFormMarkup_bug_with_utf8_values(self): postargs = { 'openid.ns': OPENID2_NS, 'openid.mode': 'checkid_setup', 'openid.identity': 'http://bogus.example.invalid:port/', 'openid.assoc_handle': 'FLUB', 'openid.return_to': 'Neverland', 'ünicöde_key': 'ünicöde_välüe', } m = Message.fromPostArgs(postargs) html = m.toFormMarkup(self.action_url, self.form_tag_attrs, self.submit_text) self.assertIn('ünicöde_key', html) self.assertIn('ünicöde_välüe', html) self.assertNotIn('ünicöde_key', html, 'UTF-8 bytes should not convert to XML character references') self.assertNotIn('ünicöde_välüe', html, 'UTF-8 bytes should not convert to XML character references')
def run(): trust_root = consumer_url consumer = GenericConsumer(store) setConsumerSession(consumer) request = consumer.begin(endpoint) return_to = consumer_url m = request.getMessage(trust_root, return_to, immediate) redirect_url = request.redirectURL(trust_root, return_to, immediate) parsed = urlparse.urlparse(redirect_url) qs = parsed[4] q = parseQuery(qs) new_return_to = q['openid.return_to'] del q['openid.return_to'] assert q == { 'openid.mode':mode, 'openid.identity':delegate_url, 'openid.trust_root':trust_root, 'openid.assoc_handle':fetcher.assoc_handle, }, (q, user_url, delegate_url, mode) assert new_return_to.startswith(return_to) assert redirect_url.startswith(server_url) parsed = urlparse.urlparse(new_return_to) query = parseQuery(parsed[4]) query.update({ 'openid.mode':'id_res', 'openid.return_to':new_return_to, 'openid.identity':delegate_url, 'openid.assoc_handle':fetcher.assoc_handle, }) assoc = store.getAssociation(server_url, fetcher.assoc_handle) message = Message.fromPostArgs(query) message = assoc.signMessage(message) info = consumer.complete(message, request.endpoint, new_return_to) assert info.status == SUCCESS, info.message assert info.identity_url == user_url
def test_unreachableRealm(self): self.request = dummyRequest() id_url = util.getViewURL(self.request, views.idPage) # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.identity': id_url, 'openid.return_to': 'http://unreachable.invalid/%s' % (self.id(),), 'openid.sreg.required': 'postcode', }) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request) response = views.showDecidePage(self.request, self.openid_request) self.assertContains(response, 'trust_root_valid is Unreachable')
def test_unreachableRealm(self): self.request = dummyRequest() id_url = util.getViewURL(self.request, views.idPage) # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.identity': id_url, 'openid.return_to': 'http://unreachable.invalid/%s' % (self.id(),), 'openid.sreg.required': 'postcode', }) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request) response = views.showDecidePage(self.request, self.openid_request) self.failUnless('trust_root_valid is Unreachable' in response.content, response)
def setUp(self): self.request = dummyRequest() id_url = util.getViewURL(self.request, views.idPage) # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.identity': id_url, 'openid.return_to': 'http://127.0.0.1/%s' % (self.id(), ), 'openid.sreg.required': 'postcode', }) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request)
def setUp(self): self.request = dummyRequest() id_url = urljoin('http://example.cz/', reverse('server:local_id')) # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.identity': id_url, 'openid.return_to': 'http://127.0.0.1/%s' % (self.id(), ), 'openid.sreg.required': 'postcode', }) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request)
def test_toFormMarkup_bug_with_utf8_values(self): postargs = { 'openid.ns': OPENID2_NS, 'openid.mode': 'checkid_setup', 'openid.identity': 'http://bogus.example.invalid:port/', 'openid.assoc_handle': 'FLUB', 'openid.return_to': 'Neverland', 'ünicöde_key': 'ünicöde_välüe', } m = Message.fromPostArgs(postargs) # Calling m.toFormMarkup with lxml used for ElementTree will throw # a ValueError. html = m.toFormMarkup(self.action_url, self.form_tag_attrs, self.submit_text) # Using the (c)ElementTree from stdlib will result in the UTF-8 # encoded strings to be converted to XML character references, # "ünicöde_key" becomes "ünicöde_key" and # "ünicöde_välüe" becomes "ünicöde_välüe" self.assertNotIn('ünicöde_key', html, 'UTF-8 bytes should not convert to XML character references') self.assertNotIn('ünicöde_välüe', html, 'UTF-8 bytes should not convert to XML character references')
def test_unreachableRealm(self): self.request = dummyRequest() id_url = urljoin('http://example.cz/', reverse('server:local_id')) # Set up the OpenID request we're responding to. op_endpoint = 'http://127.0.0.1:8080/endpoint' message = Message.fromPostArgs({ 'openid.mode': 'checkid_setup', 'openid.identity': id_url, 'openid.return_to': 'http://unreachable.invalid/%s' % (self.id(), ), 'openid.sreg.required': 'postcode', }) self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint) views.setRequest(self.request, self.openid_request) response = views.showDecidePage(self.request, self.openid_request) self.assertContains(response, 'trust_root_valid is Unreachable')
def test_getAliasedArgSuccess(self): msg = Message.fromPostArgs({'openid.ns.test': 'urn://foo', 'openid.test.flub': 'bogus'}) actual_uri = msg.getAliasedArg('ns.test', no_default) self.assertEqual("urn://foo", actual_uri)
data['openid_login_oidrequest'] = oidrequest # cb_filelist will show a login page return False elif oidrequest.mode in ['associate', 'check_authentication']: return respond(request, oidserver.handleRequest(oidrequest)) else: # cb_filelist() will show an info page about this endpoint return False except OpenIDServer.ProtocolError, why: return respond(request, why) elif http['PATH_INFO'] == trigger + '/login': try: message = Message.fromPostArgs(form) endpoint = config['base_url'] + trigger oidrequest = OpenIDServer.CheckIDRequest.fromMessage( message, endpoint) except: exception = traceback.format_exception(*sys.exc_info()) data['openid_error'] = ('Error decoding login request:\n%s\n%s' % (str(form), '\n'.join(exception))) # cb_filelist() will show an error page return False if form.has_key('continue') and form.has_key('password'): if form['password'] == config['openid_password']: if form.get('remember', '') == 'yes': tools.getLogger().info( 'Setting cookie to remember openid login')
def login_complete(request): # Get addres where to redirect after the login redirect_to = sanitise_redirect_url( request.session.get(mojeid_settings.MOJEID_SESSION_NEXT_PAGE_ATTR)) attribute_set = request.session.get(SESSION_ATTR_SET_KEY, 'default') # clean the session if mojeid_settings.MOJEID_SESSION_NEXT_PAGE_ATTR in request.session: del request.session[mojeid_settings.MOJEID_SESSION_NEXT_PAGE_ATTR] if SESSION_ATTR_SET_KEY in request.session: del request.session[SESSION_ATTR_SET_KEY] # Get OpenID response and test whether it is valid endpoint = create_service() message = Message.fromPostArgs(request.REQUEST) consumer = MojeIDConsumer(DjangoOpenIDStore()) try: openid_response = consumer.complete( message, endpoint, request.build_absolute_uri()) except HTTPFetchingError: # if not using association and can't contact MojeID server return render_failure(request, errors.EndpointError()) # Check whether the user is already logged in user_orig = OpenIDBackend.get_user_from_request(request) user_model = get_user_model() if openid_response.status == SUCCESS: try: if user_orig: # Send a signal to obtain HttpResponse resp = associate_user.send( sender=__name__, request=request, openid_response=openid_response, attribute_set=attribute_set, redirect=redirect_to ) resp = [r[1] for r in resp if isinstance(r[1], HttpResponse)] if resp: # Return first valid response return resp[0] # Create association with currently logged in user OpenIDBackend.associate_openid_response(user_orig, openid_response) else: # Authenticate mojeID user. # Send a signal to obtain HttpResponse resp = authenticate_user.send( sender=__name__, request=request, openid_response=openid_response, attribute_set=attribute_set, redirect=redirect_to ) resp = [r[1] for r in resp if isinstance(r[1], HttpResponse)] if resp: # Return first valid response return resp[0] # Perform a default action user_new = OpenIDBackend.authenticate_using_all_backends( openid_response=openid_response, attribute_set=attribute_set) if not user_new: # Failed to create a user return render_failure(request, errors.UnknownUser()) if not OpenIDBackend.is_user_active(user_new): # user is deactivated return render_failure(request, errors.DisabledAccount(user_new)) # Create an association with the new user OpenIDBackend.associate_user_with_session(request, user_new) except DjangoOpenIDException as e: # Something went wrong user_id = None try: # Try to get user id user_id = UserOpenID.objects.get(claimed_id=openid_response.identity_url).user_id except (UserOpenID.DoesNotExist, user_model.DoesNotExist): # Report an error with identity_url user_login_report.send( sender=__name__, request=request, username=openid_response.identity_url, method='openid', success=False ) # Report an error with the username user_login_report.send( sender=__name__, request=request, username=openid_response.identity_url, user_id=user_id, method='openid', success=False ) # Render the failure page return render_failure(request, errors.AuthenticationFailed(e)) response = HttpResponseRedirect(redirect_to) # Send signal to log the successful login attempt user_login_report.send( sender=__name__, request=request, user_id=user_orig.id if user_orig else user_new.id, method='openid', success=True ) return response # Render other failures elif openid_response.status == FAILURE: user_login_report.send( sender=__name__, request=request, username=openid_response.identity_url, method='openid', success=False ) return render_failure(request, errors.OpenIDAuthenticationFailed(openid_response)) elif openid_response.status == CANCEL: user_login_report.send( sender=__name__, request=request, username=openid_response.identity_url, method='openid', success=False ) return render_failure(request, errors.OpenIDAuthenticationCanceled()) else: user_login_report.send( sender=__name__, request=request, username=openid_response.identity_url, method='openid', success=False ) return render_failure(request, errors.OpenIDUnknownResponseType(openid_response))
def test_getAliasedArgFailure(self): msg = Message.fromPostArgs({'openid.test.flub': 'bogus'}) self.assertRaises(KeyError, msg.getAliasedArg, 'ns.test', no_default)
def setUp(self): self.msg = Message.fromPostArgs({'openid.mode': 'error', 'openid.error': 'unit test', 'openid.ns': OPENID1_NS})
def setUp(self): self.msg = Message.fromPostArgs({'openid.mode': 'error', 'openid.error': 'unit test', 'openid.ns': OPENID2_NS}) self.msg.setArg(BARE_NS, "xey", "value")
def test_toPostArgs_bug_with_utf8_encoded_values(self): msg = Message.fromPostArgs({'openid.mode': 'error', 'openid.error': 'unit test', 'openid.ns': OPENID2_NS}) msg.setArg(BARE_NS, 'ünicöde_key', 'ünicöde_välüe') post_args = {'openid.mode': 'error', 'openid.error': 'unit test', 'openid.ns': OPENID2_NS, 'ünicöde_key': 'ünicöde_välüe'} self.assertEqual(msg.toPostArgs(), post_args)
def test_toFormMarkup(self): m = Message.fromPostArgs(self.postargs) html = m.toFormMarkup(self.action_url, self.form_tag_attrs, self.submit_text) self._checkForm(html, m, self.action_url, self.form_tag_attrs, self.submit_text)