Exemplo n.º 1
0
    def setUp(self):
        fetchers.setDefaultFetcher(
            TestFetcher(self.base_url), wrap_exceptions=False)

        self.input_url, self.expected = discoverdata.generateResult(
            self.base_url, self.input_name, self.id_name, self.result_name,
            self.success)
Exemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        """
        Accepts additional keyword arguments:

        :param hostname:
            The hostname of the ESGF OpenID provider. Default: localhost

        :param provider_url:
            The provider identifier url template. Default: https://{hostname}/esgf-idp/openid/{username}
        """
        super(ESGFOpenID, self).__init__(*args, **kwargs)

        self.hostname = self._kwarg(kwargs, 'hostname', 'localhost')
        self.provider_url = self._kwarg(
            kwargs, 'provider_url',
            'https://{hostname}/esgf-idp/openid/{username}')
        self.ax_required = []  # ceda does not provide email

        # if username is given set provider identifier using the provider url
        if 'username' in self.params:
            self.username = self.params.get('username')
            self.identifier = self.provider_url.format(hostname=self.hostname,
                                                       username=self.username)

        # use fetcher with disabled ssl verification
        setDefaultFetcher(MyFetcher())
Exemplo n.º 3
0
 def tearDown(self):
     super(TestOpenIDLogin, self).tearDown()
     setDefaultFetcher(None)
     if self.orig_sso_server_url == self.missing_sso_server_url:
         del settings.OPENID_SSO_SERVER_URL
     else:
         settings.OPENID_SSO_SERVER_URL = self.orig_sso_server_url
Exemplo n.º 4
0
    def __init__(self,
                 openid_provider,
                 check_certificate=True,
                 **kwargs):
        unknown = []
        self.permissions = {}
        for group in kwargs:
            self.permissions[group] = []
            for perm in kwargs[group]:
                if perm in Authz.knownActions:
                    self.permissions[group].append(perm)
                else:
                    unknown.append(perm)

        self.openid_provider = openid_provider
        self.sessions = SessionManager()
        self.init_childs = False
        if not check_certificate:
            setDefaultFetcher(Urllib2Fetcher())
        # This makes us get self.master as per baseweb.py:472
        self.auth = self
        # This makes the login form be a link
        self.useHttpHeader = True
        self.httpLoginUrl = '/_openid_start/'

        if unknown != []:
            raise ValueError('Unknown authorization action(s) ' +
                             ', '.join(unknown))
Exemplo n.º 5
0
    def setUp(self):
        fetchers.setDefaultFetcher(
            TestFetcher(self.base_url), wrap_exceptions=False)

        self.input_url, self.expected = discoverdata.generateResult(
            self.base_url, self.input_name, self.id_name, self.result_name,
            self.success)
Exemplo n.º 6
0
 def tearDown(self):
     super(TestOpenIDLogin, self).tearDown()
     setDefaultFetcher(None)
     if self.orig_sso_server_url == self.missing_sso_server_url:
         del settings.OPENID_SSO_SERVER_URL
     else:
         settings.OPENID_SSO_SERVER_URL = self.orig_sso_server_url
Exemplo n.º 7
0
    def init_app(self, app):
        """ Constructor for the Flask application. """
        self.app = app
        app.config.setdefault('FAS_OPENID_ENDPOINT',
                              'https://id.fedoraproject.org/openid/')
        app.config.setdefault('FAS_OPENID_CHECK_CERT', True)

        if not self.app.config['FAS_OPENID_CHECK_CERT']:
            setDefaultFetcher(Urllib2Fetcher())

        # json_encoder is only available from flask 0.10
        version = flask.__version__.split('.')
        assume_recent = False
        try:
            major = int(version[0])
            minor = int(version[1])
        except ValueError:
            # We'll assume we're using a recent enough flask as the packages
            # of old versions used sane version numbers.
            assume_recent = True

        if assume_recent or (major > 0 or minor >= 10):
            self.app.json_encoder = FASJSONEncoder

        @app.route('/_flask_fas_openid_handler/', methods=['GET', 'POST'])
        def flask_fas_openid_handler():
            """ Endpoint for OpenID results. """
            return self._handle_openid_request()

        app.before_request(self._check_session)
Exemplo n.º 8
0
    def __init__(self,
                 openid_provider,
                 check_certificate=True,
                 **kwargs):
        unknown = []
        self.permissions = {}
        for group in kwargs:
            # Work around the limitations of python identifiers:
            # python identifiers don't support dashes, while unix group names do
            # This is admittedly a hack, but if you have a better way: a PR is welcome
            group = group.replace('_DASH_', '-')

            self.permissions[group] = []
            for perm in kwargs[group]:
                if perm in Authz.knownActions:
                    self.permissions[group].append(perm)
                else:
                    unknown.append(perm)

        self.openid_provider = openid_provider
        self.sessions = SessionManager()
        self.init_childs = False
        if not check_certificate:
            setDefaultFetcher(Urllib2Fetcher())
        # This makes us get self.master as per baseweb.py:472
        self.auth = self
        # This makes the login form be a link
        self.useHttpHeader = True

        if unknown != []:
            raise ValueError('Unknown authorization action(s) ' +
                             ', '.join(unknown))
Exemplo n.º 9
0
    def testAddingProtocol(self):
        f = ErrorRaisingFetcher(RuntimeError())
        fetchers.setDefaultFetcher(f, wrap_exceptions=False)

        try:
            discover.discover('users.stompy.janrain.com:8000/x')
        except DiscoveryFailure, why:
            self.fail('failed to parse url with port correctly')
Exemplo n.º 10
0
def set_default_openid_fetcher():
    # Make sure we're using the same fetcher that we use in production, even
    # if pycurl is installed.
    fetcher = Urllib2Fetcher()
    if config.launchpad.enable_test_openid_provider:
        cafile = os.path.join(config.root, "configs/development/launchpad.crt")
        fetcher.urlopen = partial(urllib2.urlopen, cafile=cafile)
    setDefaultFetcher(fetcher)
Exemplo n.º 11
0
    def testAddingProtocol(self):
        f = ErrorRaisingFetcher(RuntimeError())
        fetchers.setDefaultFetcher(f, wrap_exceptions=False)

        try:
            discover.discover('users.stompy.janrain.com:8000/x')
        except DiscoveryFailure, why:
            self.fail('failed to parse url with port correctly')
Exemplo n.º 12
0
    def tearDown(self):
        settings.OPENID_CREATE_USERS = self.old_create_users
        settings.OPENID_UPDATE_DETAILS_FROM_SREG = self.old_update_details
        settings.OPENID_SSO_SERVER_URL = self.old_sso_server_url
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING = self.old_teams_map

        setDefaultFetcher(None)
        super(RelyingPartyTests, self).tearDown()
Exemplo n.º 13
0
 def get_consumer(self):
     """Returns a Consumer instance.
     """
     if not self.consumer:
         fetchers.setDefaultFetcher(fetcher.UrlfetchFetcher())
         self.consumer = Consumer(self.session_args, store.DatastoreStore())
   
     return self.consumer
Exemplo n.º 14
0
  def get_consumer(self):
    """Returns a Consumer instance.
    """
    if not self.consumer:
      setDefaultFetcher(Urllib2Fetcher())
      self.consumer = Consumer(self.session, store.DatastoreStore())

    return self.consumer
Exemplo n.º 15
0
    def test(self):
        for responses in self.cases:
            url = responses[0].final_url
            status = responses[-1].status

            fetcher = SimpleMockFetcher(responses)
            fetchers.setDefaultFetcher(fetcher)
            self.runOneTest(url, status)
            fetchers.setDefaultFetcher(None)
Exemplo n.º 16
0
    def test(self):
        for responses in self.cases:
            url = responses[0].final_url
            status = responses[-1].status

            fetcher = SimpleMockFetcher(responses)
            fetchers.setDefaultFetcher(fetcher)
            self.runOneTest(url, status)
            fetchers.setDefaultFetcher(None)
Exemplo n.º 17
0
    def setUp(self):
        CatchLogs.setUp(self)
        self.store = memstore.MemoryStore()

        self.consumer = self.consumer_class(self.store)

        self._orig_fetcher = fetchers.getDefaultFetcher()
        self.fetcher = MockFetcher()
        fetchers.setDefaultFetcher(self.fetcher)
Exemplo n.º 18
0
    def get_consumer(self):
        """Returns a Consumer instance.
    """
        if not self.consumer:
            fetchers.setDefaultFetcher(fetcher.UrlfetchFetcher())
            if not self.load_session():
                return
            self.consumer = Consumer(self.session_args, store.DatastoreStore())

        return self.consumer
Exemplo n.º 19
0
    def tearDown(self):
        settings.LOGIN_REDIRECT_URL = self.old_login_redirect_url
        settings.OPENID_CREATE_USERS = self.old_create_users
        settings.OPENID_UPDATE_DETAILS_FROM_SREG = self.old_update_details
        settings.OPENID_SSO_SERVER_URL = self.old_sso_server_url
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING = self.old_teams_map
        settings.OPENID_USE_AS_ADMIN_LOGIN = self.old_use_as_admin_login

        setDefaultFetcher(None)
        super(RelyingPartyTests, self).tearDown()
Exemplo n.º 20
0
    def tearDown(self):
        settings.LOGIN_REDIRECT_URL = self.old_login_redirect_url
        settings.OPENID_CREATE_USERS = self.old_create_users
        settings.OPENID_UPDATE_DETAILS_FROM_SREG = self.old_update_details
        settings.OPENID_SSO_SERVER_URL = self.old_sso_server_url
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING = self.old_teams_map
        settings.OPENID_USE_AS_ADMIN_LOGIN = self.old_use_as_admin_login

        setDefaultFetcher(None)
        super(RelyingPartyTests, self).tearDown()
Exemplo n.º 21
0
 def setUp(self):
     super(TestOpenIDLogin, self).setUp()
     # Use StubOpenIDProvider and _identity_url as our fixed SSO so that
     # we always get a successful OpenID response for _identity_url.
     self.provider = StubOpenIDProvider('http://example.com/')
     setDefaultFetcher(self.provider, wrap_exceptions=False)
     self.missing_sso_server_url = object()
     self.orig_sso_server_url = getattr(settings, 'OPENID_SSO_SERVER_URL',
                                        self.missing_sso_server_url)
     settings.OPENID_SSO_SERVER_URL = self._identity_url
     self.client = TestClient()
Exemplo n.º 22
0
 def setUp(self):
     super(TestOpenIDLogin, self).setUp()
     # Use StubOpenIDProvider and _identity_url as our fixed SSO so that
     # we always get a successful OpenID response for _identity_url.
     self.provider = StubOpenIDProvider('http://example.com/')
     setDefaultFetcher(self.provider, wrap_exceptions=False)
     self.missing_sso_server_url = object()
     self.orig_sso_server_url = getattr(
         settings, 'OPENID_SSO_SERVER_URL', self.missing_sso_server_url)
     settings.OPENID_SSO_SERVER_URL = self._identity_url
     self.client = TestClient()
Exemplo n.º 23
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     from openid import fetchers
     import openidgae.fetcher
     fetchers.setDefaultFetcher(openidgae.fetcher.UrlfetchFetcher())
 
     # Switch logger to use logging package instead of stderr
     from openid import oidutil
     def myLoggingFunction(message, level=0):
         import logging
         logging.info(message)
     oidutil.log = myLoggingFunction
Exemplo n.º 24
0
    def test_notWrapped(self):
        """Make sure that if we set a non-wrapped fetcher as default,
        it will not wrap exceptions."""
        # A fetcher that will raise an exception when it encounters a
        # host that will not resolve
        fetcher = fetchers.Urllib2Fetcher()
        fetchers.setDefaultFetcher(fetcher, wrap_exceptions=False)

        self.assertNotIsInstance(fetchers.getDefaultFetcher(), fetchers.ExceptionWrappingFetcher)

        with self.assertRaises(URLError):
            fetchers.fetch('http://invalid.janrain.com/')
Exemplo n.º 25
0
    def _init_app(self, app):
        app.config.setdefault("FAS_OPENID_ENDPOINT", "http://id.fedoraproject.org/")
        app.config.setdefault("FAS_OPENID_CHECK_CERT", True)

        if not self.app.config["FAS_OPENID_CHECK_CERT"]:
            setDefaultFetcher(Urllib2Fetcher())

        @app.route("/_flask_fas_openid_handler/", methods=["GET", "POST"])
        def flask_fas_openid_handler():
            return self._handle_openid_request()

        app.before_request(self._check_session)
Exemplo n.º 26
0
    def setUp(self):
        self.client = Client(test_app, Response)

        self.fetcher = FakeFetcher(self.client)
        fetchers.setDefaultFetcher(self.fetcher, False)

        self.consumer_session = dict()
        self.assoc_store = MemoryStore()

        self.consumer = Consumer(
            self.consumer_session,
            self.assoc_store)
Exemplo n.º 27
0
    def test_notWrapped(self):
        """Make sure that if we set a non-wrapped fetcher as default,
        it will not wrap exceptions."""
        # A fetcher that will raise an exception when it encounters a
        # host that will not resolve
        fetcher = fetchers.Urllib2Fetcher()
        fetchers.setDefaultFetcher(fetcher, wrap_exceptions=False)

        self.assertNotIsInstance(fetchers.getDefaultFetcher(),
                                 fetchers.ExceptionWrappingFetcher)

        with self.assertRaises(URLError):
            fetchers.fetch('http://invalid.janrain.com/')
Exemplo n.º 28
0
    def _init_app(self, app):
        app.config.setdefault('FAS_OPENID_ENDPOINT',
                              'http://id.fedoraproject.org/')
        app.config.setdefault('FAS_OPENID_CHECK_CERT', True)

        if not self.app.config['FAS_OPENID_CHECK_CERT']:
            setDefaultFetcher(Urllib2Fetcher())

        @app.route('/_flask_fas_openid_handler/', methods=['GET', 'POST'])
        def flask_fas_openid_handler():
            return self._handle_openid_request()

        app.before_request(self._check_session)
Exemplo n.º 29
0
    def load(self, info):
        events.bind('no_password_login_attempt', 'openid', _checkOpenIdUser)
        info['apiRoot'].openid = rest.OpenId()
        SettingDefault.defaults[constants.PluginSettings.PROVIDERS] = []

        if 'GIRDER_REQUESTS_VERIFY' in os.environ:
            path = os.environ['GIRDER_REQUESTS_VERIFY']
            if not os.path.isfile(path):
                raise Exception('Requests cert not found: %s' % path)
            # We use a custom fetcher class and set it as the default to support customization
            # of the "verify" parameter of the requests session
            logger.info('OpenID: using verify value=%s' % path)
            setDefaultFetcher(_CustomCAFetcher(path), wrap_exceptions=False)
Exemplo n.º 30
0
    def _init_app(self, app):
        app.config.setdefault('FAS_OPENID_ENDPOINT',
                              'http://id.fedoraproject.org/')
        app.config.setdefault('FAS_OPENID_CHECK_CERT', True)

        if not self.app.config['FAS_OPENID_CHECK_CERT']:
            setDefaultFetcher(Urllib2Fetcher())

        @app.route('/_flask_fas_openid_handler/', methods=['GET', 'POST'])
        def flask_fas_openid_handler():
            return self._handle_openid_request()

        app.before_request(self._check_session)
Exemplo n.º 31
0
    def setUp(self):
        super(RelyingPartyTests, self).setUp()
        self.provider = StubOpenIDProvider('http://example.com/')
        setDefaultFetcher(self.provider, wrap_exceptions=False)

        self.old_create_users = getattr(settings, 'OPENID_CREATE_USERS', False)
        self.old_update_details = getattr(settings, 'OPENID_UPDATE_DETAILS_FROM_SREG', False)
        self.old_sso_server_url = getattr(settings, 'OPENID_SSO_SERVER_URL')
        self.old_teams_map = getattr(settings, 'OPENID_LAUNCHPAD_TEAMS_MAPPING', {})

        settings.OPENID_CREATE_USERS = False
        settings.OPENID_UPDATE_DETAILS_FROM_SREG = False
        settings.OPENID_SSO_SERVER_URL = None
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING = {}
Exemplo n.º 32
0
def main(host, port, weak_ssl=False):
    # Instantiate OpenID consumer store and OpenID consumer.  If you
    # were connecting to a database, you would create the database
    # connection and instantiate an appropriate store here.
    store = memstore.MemoryStore()
    if weak_ssl:
        setDefaultFetcher(Urllib2Fetcher())

    addr = (host, port)
    server = OpenIDHTTPServer(store, addr, OpenIDRequestHandler)

    print 'Server running at:'
    print server.base_url
    server.serve_forever()
Exemplo n.º 33
0
    def _init_app(self, app):
        """ Constructor for the flask application. """
        app.config.setdefault('FAS_OPENID_ENDPOINT',
                              'http://id.fedoraproject.org/')
        app.config.setdefault('FAS_OPENID_CHECK_CERT', True)

        if not self.app.config['FAS_OPENID_CHECK_CERT']:
            setDefaultFetcher(Urllib2Fetcher())

        @app.route('/_flask_fas_openid_handler/', methods=['GET', 'POST'])
        def flask_fas_openid_handler():
            """ Add endpoint handling the openid requests. """
            return self._handle_openid_request()

        app.before_request(self._check_session)
Exemplo n.º 34
0
    def _init_app(self, app):
        """ Constructor for the flask application. """
        app.config.setdefault('FAS_OPENID_ENDPOINT',
                              'http://id.fedoraproject.org/')
        app.config.setdefault('FAS_OPENID_CHECK_CERT', True)

        if not self.app.config['FAS_OPENID_CHECK_CERT']:
            setDefaultFetcher(Urllib2Fetcher())

        @app.route('/_flask_fas_openid_handler/', methods=['GET', 'POST'])
        def flask_fas_openid_handler():
            """ Add endpoint handling the openid requests. """
            return self._handle_openid_request()

        app.before_request(self._check_session)
Exemplo n.º 35
0
    def setUp(self):
        super(RelyingPartyTests, self).setUp()
        self.provider = StubOpenIDProvider('http://example.com/')
        setDefaultFetcher(self.provider, wrap_exceptions=False)

        self.old_login_redirect_url = getattr(settings, 'LOGIN_REDIRECT_URL', '/accounts/profile/')
        self.old_create_users = getattr(settings, 'OPENID_CREATE_USERS', False)
        self.old_update_details = getattr(settings, 'OPENID_UPDATE_DETAILS_FROM_SREG', False)
        self.old_sso_server_url = getattr(settings, 'OPENID_SSO_SERVER_URL', None)
        self.old_teams_map = getattr(settings, 'OPENID_LAUNCHPAD_TEAMS_MAPPING', {})
        self.old_use_as_admin_login = getattr(settings, 'OPENID_USE_AS_ADMIN_LOGIN', False)

        settings.OPENID_CREATE_USERS = False
        settings.OPENID_UPDATE_DETAILS_FROM_SREG = False
        settings.OPENID_SSO_SERVER_URL = None
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING = {}
        settings.OPENID_USE_AS_ADMIN_LOGIN = False
Exemplo n.º 36
0
    def setUp(self):
        super(RelyingPartyTests, self).setUp()
        self.provider = StubOpenIDProvider('http://example.com/')
        setDefaultFetcher(self.provider, wrap_exceptions=False)

        self.old_login_redirect_url = getattr(settings, 'LOGIN_REDIRECT_URL', '/accounts/profile/')
        self.old_create_users = getattr(settings, 'OPENID_CREATE_USERS', False)
        self.old_update_details = getattr(settings, 'OPENID_UPDATE_DETAILS_FROM_SREG', False)
        self.old_sso_server_url = getattr(settings, 'OPENID_SSO_SERVER_URL')
        self.old_teams_map = getattr(settings, 'OPENID_LAUNCHPAD_TEAMS_MAPPING', {})
        self.old_use_as_admin_login = getattr(settings, 'OPENID_USE_AS_ADMIN_LOGIN', False)

        settings.OPENID_CREATE_USERS = False
        settings.OPENID_UPDATE_DETAILS_FROM_SREG = False
        settings.OPENID_SSO_SERVER_URL = None
        settings.OPENID_LAUNCHPAD_TEAMS_MAPPING = {}
        settings.OPENID_USE_AS_ADMIN_LOGIN = False
Exemplo n.º 37
0
def main():
  fetchers.setDefaultFetcher(UrlfetchFetcher()) 
  application = webapp.WSGIApplication(
                                       [('/', MainPage),
                                        ('/home',HomePage),
                                        ('/confirm', Confirm),
                                        ('/delete', Delete),
                                        ('/login', LoginPage),
                                        ('/logout', LogoutSubmit),
                                        ('/openid-start', OpenIDStartSubmit),
                                        ('/openid-finish', OpenIDFinish),
                                        ('/about', AboutPage),
                                        ('/rpxrds', RelyingPartyXRDS),
                                        ('/googlehostedservice.html', GoogleAppsCode),
                                        (r'/verify/(.*)', Verify)
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)
Exemplo n.º 38
0
def main(host, port, data_path, weak_ssl=False):
    # Instantiate OpenID consumer store and OpenID consumer.  If you
    # were connecting to a database, you would create the database
    # connection and instantiate an appropriate store here.
    if data_path:
        store = filestore.FileOpenIDStore(data_path)
    else:
        store = memstore.MemoryStore()

    if weak_ssl:
        setDefaultFetcher(Urllib2Fetcher())

    addr = (host, port)
    server = OpenIDHTTPServer(store, addr, OpenIDRequestHandler)

    print 'Server running at:'
    print server.base_url
    server.serve_forever()
Exemplo n.º 39
0
 def _initIdPValidation(self, idpWhitelistConfigFilePath):
     """Initialise M2Crypto based urllib2 HTTPS handler to enable SSL 
     authentication of OpenID Providers"""
     log.info("Setting parameters for SSL Authentication of OpenID "
              "Provider ...")
     
     idPValidationDriver = SSLIdPValidationDriver(
                             idpConfigFilePath=idpWhitelistConfigFilePath)
         
     # Force Python OpenID library to use Urllib2 fetcher instead of the 
     # Curl based one otherwise the M2Crypto SSL handler will be ignored.
     setDefaultFetcher(Urllib2Fetcher())
     
     log.debug("Setting the M2Crypto SSL handler ...")
     
     opener = urllib2.OpenerDirector()            
     opener.add_handler(FlagHttpsOnlyHandler())
     opener.add_handler(HTTPSHandler(idPValidationDriver.ctx))
     
     urllib2.install_opener(opener)
Exemplo n.º 40
0
    def test_notWrapped(self):
        """Make sure that if we set a non-wrapped fetcher as default,
        it will not wrap exceptions."""
        # A fetcher that will raise an exception when it encounters a
        # host that will not resolve
        fetcher = fetchers.Urllib2Fetcher()
        fetchers.setDefaultFetcher(fetcher, wrap_exceptions=False)

        self.assertFalse(isinstance(fetchers.getDefaultFetcher(),
                               fetchers.ExceptionWrappingFetcher))

        try:
            fetchers.fetch('http://invalid.janrain.com/')
        except fetchers.HTTPFetchingError:
            self.fail('Should not be wrapping exception')
        except Exception as exc:
            self.assertIsInstance(exc, urllib.error.URLError)
            pass
        else:
            self.fail('Should have raised an exception')
Exemplo n.º 41
0
    def test_notWrapped(self):
        """Make sure that if we set a non-wrapped fetcher as default,
        it will not wrap exceptions."""
        # A fetcher that will raise an exception when it encounters a
        # host that will not resolve
        fetcher = fetchers.Urllib2Fetcher()
        fetchers.setDefaultFetcher(fetcher, wrap_exceptions=False)

        self.failIf(isinstance(fetchers.getDefaultFetcher(), fetchers.ExceptionWrappingFetcher))

        try:
            fetchers.fetch("http://invalid.janrain.com/")
        except fetchers.HTTPFetchingError:
            self.fail("Should not be wrapping exception")
        except:
            exc = sys.exc_info()[1]
            self.failUnless(isinstance(exc, urllib2.URLError), exc)
            pass
        else:
            self.fail("Should have raised an exception")
Exemplo n.º 42
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')
Exemplo n.º 43
0
    def test_notWrapped(self):
        """Make sure that if we set a non-wrapped fetcher as default,
        it will not wrap exceptions."""
        # A fetcher that will raise an exception when it encounters a
        # host that will not resolve
        fetcher = fetchers.Urllib2Fetcher()
        fetchers.setDefaultFetcher(fetcher, wrap_exceptions=False)

        self.assertFalse(
            isinstance(fetchers.getDefaultFetcher(),
                       fetchers.ExceptionWrappingFetcher))

        try:
            fetchers.fetch('http://invalid.janrain.com/')
        except fetchers.HTTPFetchingError:
            self.fail('Should not be wrapping exception')
        except Exception as exc:
            self.assertIsInstance(exc, urllib.error.URLError)
            pass
        else:
            self.fail('Should have raised an exception')
Exemplo n.º 44
0
    def __init__(self, *args, **kwargs):
        """
        Accepts additional keyword arguments:
        
        :param hostname:
            The hostname of the ESGF OpenID provider. Default: localhost

        :param provider_url:
            The provider identifier url template. Default: https://{hostname}/esgf-idp/openid/{username}
        """
        super(ESGFOpenID, self).__init__(*args, **kwargs)

        self.hostname = self._kwarg(kwargs, 'hostname', 'localhost')
        self.provider_url = self._kwarg(kwargs, 'provider_url', 'https://{hostname}/esgf-idp/openid/{username}')

        # if username is given set provider identifier using the provider url
        if 'username' in self.params:
            self.username = self.params.get('username')
            self.identifier = self.provider_url.format(hostname=self.hostname, username=self.username)

        # use fetcher with disabled ssl verification
        setDefaultFetcher( MyFetcher() )
Exemplo n.º 45
0
    def _initIdPValidation(self, idpWhitelistConfigFilePath):
        """Initialise M2Crypto based urllib2 HTTPS handler to enable SSL 
        authentication of OpenID Providers"""
        if _M2CRYPTO_NOT_INSTALLED:
            raise ImportError("M2Crypto is required for SSL-based IdP "
                              "validation but it is not installed.")

        log.info("Setting parameters for SSL Authentication of OpenID "
                 "Provider ...")

        idPValidationDriver = SSLIdPValidationDriver(
            idpConfigFilePath=idpWhitelistConfigFilePath)

        # Force Python OpenID library to use Urllib2 fetcher instead of the
        # Curl based one otherwise the M2Crypto SSL handler will be ignored.
        setDefaultFetcher(Urllib2Fetcher())

        log.debug("Setting the M2Crypto SSL handler ...")

        opener = urllib2.OpenerDirector()
        opener.add_handler(FlagHttpsOnlyHandler())
        opener.add_handler(HTTPSHandler(idPValidationDriver.ctx))

        urllib2.install_opener(opener)
Exemplo n.º 46
0
 def test_setDefault(self):
     """Make sure the getDefaultFetcher returns the object set for
     setDefaultFetcher"""
     sentinel = object()
     fetchers.setDefaultFetcher(sentinel, wrap_exceptions=False)
     self.assertTrue(fetchers.getDefaultFetcher() is sentinel)
Exemplo n.º 47
0
 def test_getDefaultNotNone(self):
     """Make sure that None is never returned as a default fetcher"""
     self.assertTrue(fetchers.getDefaultFetcher() is not None)
     fetchers.setDefaultFetcher(None)
     self.assertTrue(fetchers.getDefaultFetcher() is not None)
Exemplo n.º 48
0
 def tearDown(self):
     """reset the default fetcher to None"""
     fetchers.setDefaultFetcher(None)
Exemplo n.º 49
0
 def setUp(self):
     """reset the default fetcher to None"""
     fetchers.setDefaultFetcher(None)
Exemplo n.º 50
0
 def tearDown(self):
     fetchers.setDefaultFetcher(self.oldfetcher)
Exemplo n.º 51
0
 def setUp(self):
     fetcher = SimpleMockFetcher(self.responses)
     fetchers.setDefaultFetcher(fetcher)
Exemplo n.º 52
0
logger = logging.getLogger(__name__)

user_page = Blueprint('user', __name__)


# monkey-patch uidutil.log to use the standard logging framework
openid_logger = logging.getLogger('openid')
def log_openid_messages(message, level=0):
    openid_logger.info(message)
oidutil.log = log_openid_messages


# force the use urllib2 with a timeout
fetcher = fetchers.Urllib2Fetcher()
fetcher.urlopen = lambda req: urllib2.urlopen(req, timeout=5)
fetchers.setDefaultFetcher(fetcher)


@user_page.route('/login', methods=['GET', 'POST'])
def login():
    if 'id' in session:
        return redirect(url_for('general.index'))
    errors = list(request.args.getlist('error'))
    if request.method == 'POST':
        login_method = request.form.get('login')
        if login_method == 'musicbrainz':
            return musicbrainz_login()
        elif login_method == 'google':
            return google_login()
        elif login_method == 'openid':
            return openid_login()
Exemplo n.º 53
0
 def tearDown(self):
     setDefaultFetcher(None)
Exemplo n.º 54
0
 def setUp(self):
     self.fetcher = FakeFetcher()
     setDefaultFetcher(self.fetcher)
Exemplo n.º 55
0
 def setUp(self):
     fetcher = ErrorRaisingFetcher(self.exc)
     fetchers.setDefaultFetcher(fetcher, wrap_exceptions=False)
Exemplo n.º 56
0
 def tearDown(self):
     fetchers.setDefaultFetcher(None)
Exemplo n.º 57
0
 def test_callFetch(self):
     """Make sure that fetchers.fetch() uses the default fetcher
     instance that was set."""
     fetchers.setDefaultFetcher(FakeFetcher())
     actual = fetchers.fetch('bad://url')
     self.assertTrue(actual is FakeFetcher.sentinel)
Exemplo n.º 58
0
### Tests for openid.consumer.discover.discover


class TestNormalization(unittest.TestCase):
    def testAddingProtocol(self):
        f = ErrorRaisingFetcher(RuntimeError())
        fetchers.setDefaultFetcher(f, wrap_exceptions=False)

        try:
            discover.discover('users.stompy.janrain.com:8000/x')
        except DiscoveryFailure, why:
            self.fail('failed to parse url with port correctly')
        except RuntimeError:
            pass  #expected

        fetchers.setDefaultFetcher(None)


class DiscoveryMockFetcher(object):
    redirect = None

    def __init__(self, documents):
        self.documents = documents
        self.fetchlog = []

    def fetch(self, url, body=None, headers=None):
        self.fetchlog.append((url, body, headers))
        if self.redirect:
            final_url = self.redirect
        else:
            final_url = url
Exemplo n.º 59
0
 def setUp(self):
     self.documents = self.documents.copy()
     self.fetcher = self.fetcherClass(self.documents)
     fetchers.setDefaultFetcher(self.fetcher)