class StartResponseWrapper(object): def __init__(self, start_response): self.start_response = start_response self.status = None self.headers = [] self.exc_info = None self.buffer = StringIO() # A WSGI app may delay calling start_response until the first iteration # of its generator. We track this so we know whether or not we need to # trigger an iteration before examining the response. self.called = False def wrap_start_response(self, status, headers, exc_info=None): self.headers = headers self.status = status self.exc_info = exc_info # The response has been initiated, so we have a valid code. self.called = True return self.buffer.write def finish_response(self, extra_headers): if not extra_headers: extra_headers = [] headers = self.headers + extra_headers write = self.start_response(self.status, headers, self.exc_info) if write: self.buffer.seek(0) value = self.buffer.getvalue() if value: write(value) if hasattr(write, "close"): write.close()
class StartResponseWrapper(object): def __init__(self, start_response): self.start_response = start_response self.status = None self.headers = [] self.exc_info = None self.buffer = StringIO() # A WSGI app may delay calling start_response until the first iteration # of its generator. We track this so we know whether or not we need to # trigger an iteration before examining the response. self.called = False def wrap_start_response(self, status, headers, exc_info=None): self.headers = headers self.status = status self.exc_info = exc_info # The response has been initiated, so we have a valid code. self.called = True return self.buffer.write def finish_response(self, extra_headers): if not extra_headers: extra_headers = [] headers = self.headers + extra_headers write = self.start_response(self.status, headers, self.exc_info) if write: self.buffer.seek(0) value = self.buffer.getvalue() if value: write(value) if hasattr(write, 'close'): write.close()
def __init__(self, start_response): self.start_response = start_response self.status = None self.headers = [] self.exc_info = None self.buffer = StringIO() # A WSGI app may delay calling start_response until the first iteration # of its generator. We track this so we know whether or not we need to # trigger an iteration before examining the response. self.called = False
def test_finish_response(self): from repoze.who._compat import StringIO statuses = [] headerses = [] datases = [] closededs = [] def write(data): datases.append(data) def close(): closededs.append(True) write.close = close def start_response(status, headers, exc_info=None): statuses.append(status) headerses.append(headers) return write wrapper = self._makeOne(start_response) wrapper.status = '401 Unauthorized' wrapper.headers = [('a', '1')] wrapper.buffer = StringIO('written') extra_headers = [('b', '2')] result = wrapper.finish_response(extra_headers) self.assertEqual(result, None) self.assertEqual(headerses[0], wrapper.headers + extra_headers) self.assertEqual(statuses[0], wrapper.status) self.assertEqual(datases[0], 'written') self.assertEqual(closededs[0], True)
def test_authenticate_nocreds(self): from repoze.who._compat import StringIO io = StringIO() plugin = self._makeOne(io, None) environ = self._makeEnviron() creds = {} result = plugin.authenticate(environ, creds) self.assertEqual(result, None)
def test_parse_empty_file(self): from repoze.who._compat import StringIO config = self._makeOne() config.parse(StringIO()) self.assertEqual(config.request_classifier, None) self.assertEqual(config.challenge_decider, None) self.assertEqual(config.remote_user_key, 'REMOTE_USER') self.assertEqual(len(config.plugins), 0) self.assertEqual(len(config.identifiers), 0) self.assertEqual(len(config.authenticators), 0) self.assertEqual(len(config.challengers), 0) self.assertEqual(len(config.mdproviders), 0)
def test_authenticate_badline(self): from repoze.who._compat import StringIO io = StringIO('badline\nchrism:pass') def check(password, hashed): return True plugin = self._makeOne(io, check) environ = self._makeEnviron() creds = {'login': '******', 'password': '******'} result = plugin.authenticate(environ, creds) self.assertEqual(result, 'chrism')
def _makeEnviron(self, path_info='/', identifier=None): from repoze.who._compat import StringIO if identifier is None: credentials = {'login': '******', 'password': '******'} identifier = DummyIdentifier(credentials) content_type, body = encode_multipart_formdata() environ = { 'wsgi.version': (1, 0), 'wsgi.input': StringIO(body), 'wsgi.url_scheme': 'http', 'SERVER_NAME': 'www.example.com', 'SERVER_PORT': '80', 'CONTENT_TYPE': content_type, 'CONTENT_LENGTH': len(body), 'REQUEST_METHOD': 'POST', 'repoze.who.plugins': { 'cookie': identifier }, 'QUERY_STRING': 'default=1', 'PATH_INFO': path_info, } return environ
def parse(self, text): if getattr(text, 'readline', None) is None: text = StringIO(text) cp = ConfigParser(defaults={'here': self.here}) try: cp.read_file(text) except AttributeError: #pragma NO COVER Python < 3.0 cp.readfp(text) for s_id in [x for x in cp.sections() if x.startswith('plugin:')]: plugin_id = s_id[len('plugin:'):] options = dict(cp.items(s_id)) if 'use' in options: name = options.pop('use') del options['here'] obj = self._makePlugin(name, IPlugin, options) self.plugins[plugin_id] = obj if 'general' in cp.sections(): general = dict(cp.items('general')) rc = general.get('request_classifier') if rc is not None: rc = self._getPlugin(rc, IRequestClassifier) self.request_classifier = rc cd = general.get('challenge_decider') if cd is not None: cd = self._getPlugin(cd, IChallengeDecider) self.challenge_decider = cd ru = general.get('remote_user_key') if ru is not None: self.remote_user_key = ru if 'identifiers' in cp.sections(): identifiers = dict(cp.items('identifiers')) self._parsePluginSequence( self.identifiers, identifiers['plugins'], IIdentifier, ) if 'authenticators' in cp.sections(): authenticators = dict(cp.items('authenticators')) self._parsePluginSequence( self.authenticators, authenticators['plugins'], IAuthenticator, ) if 'challengers' in cp.sections(): challengers = dict(cp.items('challengers')) self._parsePluginSequence( self.challengers, challengers['plugins'], IChallenger, ) if 'mdproviders' in cp.sections(): mdproviders = dict(cp.items('mdproviders')) self._parsePluginSequence( self.mdproviders, mdproviders['plugins'], IMetadataProvider, )
def make_test_middleware(app, global_conf): """ Functionally equivalent to [plugin:redirector] use = repoze.who.plugins.redirector.RedirectorPlugin login_url = /login.html [plugin:auth_tkt] use = repoze.who.plugins.auth_tkt:AuthTktCookiePlugin secret = SEEKRIT cookie_name = oatmeal [plugin:basicauth] use = repoze.who.plugins.basicauth.BasicAuthPlugin realm = repoze.who [plugin:htpasswd] use = repoze.who.plugins.htpasswd.HTPasswdPlugin filename = <...> check_fn = repoze.who.plugins.htpasswd:crypt_check [general] request_classifier = repoze.who.classifiers:default_request_classifier challenge_decider = repoze.who.classifiers:default_challenge_decider [identifiers] plugins = authtkt basicauth [authenticators] plugins = authtkt htpasswd [challengers] plugins = redirector:browser basicauth """ # be able to test without a config file from repoze.who.plugins.basicauth import BasicAuthPlugin from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin from repoze.who.plugins.redirector import RedirectorPlugin from repoze.who.plugins.htpasswd import HTPasswdPlugin io = StringIO() for name, password in [("admin", "admin"), ("chris", "chris")]: io.write("%s:%s\n" % (name, password)) io.seek(0) def cleartext_check(password, hashed): return password == hashed # pragma NO COVERAGE htpasswd = HTPasswdPlugin(io, cleartext_check) basicauth = BasicAuthPlugin("repoze.who") auth_tkt = AuthTktCookiePlugin("secret", "auth_tkt") redirector = RedirectorPlugin("/login.html") redirector.classifications = {IChallenger: ["browser"]} # only for browser identifiers = [("auth_tkt", auth_tkt), ("basicauth", basicauth)] authenticators = [("htpasswd", htpasswd)] challengers = [("redirector", redirector), ("basicauth", basicauth)] mdproviders = [] from repoze.who.classifiers import default_request_classifier from repoze.who.classifiers import default_challenge_decider log_stream = None import os if os.environ.get("WHO_LOG"): log_stream = sys.stdout middleware = PluggableAuthenticationMiddleware( app, identifiers, authenticators, challengers, mdproviders, default_request_classifier, default_challenge_decider, log_stream=log_stream, log_level=logging.DEBUG, ) return middleware
def make_test_middleware(app, global_conf): """ Functionally equivalent to [plugin:redirector] use = repoze.who.plugins.redirector.RedirectorPlugin login_url = /login.html [plugin:auth_tkt] use = repoze.who.plugins.auth_tkt:AuthTktCookiePlugin secret = SEEKRIT cookie_name = oatmeal [plugin:basicauth] use = repoze.who.plugins.basicauth.BasicAuthPlugin realm = repoze.who [plugin:htpasswd] use = repoze.who.plugins.htpasswd.HTPasswdPlugin filename = <...> check_fn = repoze.who.plugins.htpasswd:crypt_check [general] request_classifier = repoze.who.classifiers:default_request_classifier challenge_decider = repoze.who.classifiers:default_challenge_decider [identifiers] plugins = authtkt basicauth [authenticators] plugins = authtkt htpasswd [challengers] plugins = redirector:browser basicauth """ # be able to test without a config file from repoze.who.plugins.basicauth import BasicAuthPlugin from repoze.who.plugins.auth_tkt import AuthTktCookiePlugin from repoze.who.plugins.redirector import RedirectorPlugin from repoze.who.plugins.htpasswd import HTPasswdPlugin io = StringIO() for name, password in [('admin', 'admin'), ('chris', 'chris')]: io.write('%s:%s\n' % (name, password)) io.seek(0) def cleartext_check(password, hashed): return password == hashed #pragma NO COVERAGE htpasswd = HTPasswdPlugin(io, cleartext_check) basicauth = BasicAuthPlugin('repoze.who') auth_tkt = AuthTktCookiePlugin('secret', 'auth_tkt') redirector = RedirectorPlugin('/login.html') redirector.classifications = {IChallenger: ['browser']} # only for browser identifiers = [ ('auth_tkt', auth_tkt), ('basicauth', basicauth), ] authenticators = [('htpasswd', htpasswd)] challengers = [('redirector', redirector), ('basicauth', basicauth)] mdproviders = [] from repoze.who.classifiers import default_request_classifier from repoze.who.classifiers import default_challenge_decider log_stream = None import os if os.environ.get('WHO_LOG'): log_stream = sys.stdout middleware = PluggableAuthenticationMiddleware(app, identifiers, authenticators, challengers, mdproviders, default_request_classifier, default_challenge_decider, log_stream=log_stream, log_level=logging.DEBUG) return middleware