##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# 
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
# 
##############################################################################
"""
$Id: BasicAuthTransport.py,v 1.1.1.1 2002/05/16 19:44:55 chrism Exp $

XML-RPC Basic Authentication Transport.

"""
__version__ = "$Revision: 1.1.1.1 $"[11:-2]

import xmlrpclib, base64

class BasicAuthTransport(xmlrpclib.Transport):
    def __init__(self, username=None, password=None):
        self.username=username
        self.password=password
        self.verbose = 0

    def request(self, host, handler, request_body, verbose=0):
        # issue XML-RPC request

        h = self.make_connection(host)
        if verbose:
            h.set_debuglevel(1)

        self.send_request(h, handler, request_body)
        self.send_host(h, host)
        self.send_user_agent(h)
        self.send_auth(h, self.username, self.password)
        self.send_content(h, request_body)

        errcode, errmsg, headers = h.getreply()

        if errcode != 200:
            raise ProtocolError(
                host + handler,
                errcode, errmsg,
                headers
                )

        self.verbose = verbose

        return self.parse_response(h.getfile())

    def send_auth(self, connection, username, password):
        if username is not None and password is not None:
            auth_string = base64.encodestring('%s:%s' % (username, password))
            auth_string = auth_string.replace('\012', '')
            connection.putheader("Authorization", "Basic %s" % auth_string)


