~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/HTTPTestUtil.py

mergeĀ basicĀ auth

Show diffs side-by-side

added added

removed removed

Lines of Context:
309
309
       self.old_server = self.get_secondary_server()
310
310
 
311
311
 
 
312
class BasicAuthRequestHandler(TestingHTTPRequestHandler):
 
313
    """Requires a basic authentication to process requests.
 
314
 
 
315
    This is intended to be used with a server that always and
 
316
    only use basic authentication.
 
317
    """
 
318
 
 
319
    def do_GET(self):
 
320
        tcs = self.server.test_case_server
 
321
        if tcs.auth_scheme == 'basic':
 
322
            auth_header = self.headers.get('Authorization')
 
323
            authorized = False
 
324
            if auth_header and auth_header.lower().startswith('basic '):
 
325
                coded_auth = auth_header[len('Basic '):]
 
326
                user, password = coded_auth.decode('base64').split(':')
 
327
                authorized = tcs.authorized(user, password)
 
328
            if not authorized:
 
329
                self.send_response(401)
 
330
                self.send_header('www-authenticate',
 
331
                                 'Basic realm="Thou should not pass"')
 
332
                self.end_headers()
 
333
                return
 
334
 
 
335
        TestingHTTPRequestHandler.do_GET(self)
 
336
 
 
337
 
 
338
class AuthHTTPServer(HttpServer):
 
339
    """AuthHTTPServer extends HttpServer with a dictionary of passwords.
 
340
 
 
341
    This is used as a base class for various schemes.
 
342
 
 
343
    Note that no users are defined by default, so add_user should
 
344
    be called before issuing the first request.
 
345
    """
 
346
 
 
347
    def __init__(self, request_handler, auth_scheme):
 
348
        HttpServer.__init__(self, request_handler)
 
349
        self.auth_scheme = auth_scheme
 
350
        self.password_of = {}
 
351
 
 
352
    def add_user(self, user, password):
 
353
        """Declare a user with an associated password.
 
354
 
 
355
        password can be empty, use an empty string ('') in that
 
356
        case, not None.
 
357
        """
 
358
        self.password_of[user] = password
 
359
 
 
360
    def authorized(self, user, password):
 
361
        expected_password = self.password_of.get(user, None)
 
362
        return expected_password is not None and password == expected_password
 
363
 
 
364
 
 
365
class BasicAuthHTTPServer(AuthHTTPServer):
 
366
    """An HTTP server requiring basic authentication"""
 
367
 
 
368
    def __init__(self):
 
369
        AuthHTTPServer.__init__(self, BasicAuthRequestHandler, 'basic')