예제 #1
0
 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())
예제 #2
0
 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)
예제 #3
0
 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())
예제 #4
0
 def test_bad_args(self):
     query = {
         'openid.signed':'foo',
         'closid.foo':'something',
         }
     consumer = BadArgCheckingConsumer(self.store)
     consumer._checkAuth(Message.fromPostArgs(query), 'does://not.matter')
예제 #5
0
    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')
예제 #6
0
 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)
예제 #7
0
 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)
예제 #8
0
 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")
예제 #9
0
  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.')
예제 #10
0
 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)
예제 #11
0
    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)
예제 #12
0
 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)
예제 #13
0
    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)
예제 #14
0
 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
예제 #15
0
    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')
예제 #16
0
    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)
예제 #17
0
 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)
예제 #18
0
    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)
예제 #19
0
 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)
예제 #20
0
    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',
            })
예제 #21
0
파일: tests.py 프로젝트: bearstech/OursID
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)
예제 #22
0
    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)
예제 #23
0
 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))
예제 #24
0
    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)
예제 #25
0
 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())
예제 #26
0
    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)
예제 #27
0
    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)
예제 #28
0
 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')
예제 #29
0
    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
예제 #30
0
    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')
예제 #31
0
    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)
예제 #32
0
    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)
예제 #33
0
    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)
예제 #34
0
 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')
예제 #35
0
    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')
예제 #36
0
 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)
예제 #37
0
                    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')
예제 #38
0
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))
예제 #39
0
 def test_getAliasedArgFailure(self):
     msg = Message.fromPostArgs({'openid.test.flub': 'bogus'})
     self.assertRaises(KeyError, msg.getAliasedArg, 'ns.test', no_default)
예제 #40
0
 def setUp(self):
     self.msg = Message.fromPostArgs({'openid.mode': 'error', 'openid.error': 'unit test', 'openid.ns': OPENID1_NS})
예제 #41
0
 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")
예제 #42
0
 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)
예제 #43
0
 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)