From b0c8a1ca5ae5487bcbf594957aed2d9206e5ed46 Mon Sep 17 00:00:00 2001 From: Benjamin Tayehanpour Date: Tue, 8 Mar 2016 15:13:54 +0100 Subject: [PATCH] Added HTTP Basic Authentication --- pyexchange/__init__.py | 2 +- pyexchange/connection.py | 53 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/pyexchange/__init__.py b/pyexchange/__init__.py index 1f78bb1..d8eb320 100644 --- a/pyexchange/__init__.py +++ b/pyexchange/__init__.py @@ -6,7 +6,7 @@ """ import logging from .exchange2010 import Exchange2010Service # noqa -from .connection import ExchangeNTLMAuthConnection # noqa +from .connection import ExchangeNTLMAuthConnection, ExchangeBasicAuthConnection # noqa # Silence notification of no default logging handler log = logging.getLogger("pyexchange") diff --git a/pyexchange/connection.py b/pyexchange/connection.py index 51feb5d..ab901f9 100644 --- a/pyexchange/connection.py +++ b/pyexchange/connection.py @@ -6,6 +6,7 @@ """ import requests from requests_ntlm import HttpNtlmAuth +from requests.auth import HTTPBasicAuth import logging @@ -72,3 +73,55 @@ def send(self, body, headers=None, retries=2, timeout=30, encoding=u"utf-8"): log.debug(u'Got body: {body}'.format(body=response.text)) return response.text + +class ExchangeBasicAuthConnection(ExchangeBaseConnection): + """ Connection to Exchange that uses Basic HTTP authentication """ + + def __init__(self, url, username, password, verify_certificate=True, **kwargs): + self.url = url + self.username = username + self.password = password + self.verify_certificate = verify_certificate + self.handler = None + self.session = None + self.password_manager = None + + def build_password_manager(self): + if self.password_manager: + return self.password_manager + + log.debug(u'Constructing password manager') + + self.password_manager = HTTPBasicAuth(self.username, self.password) + + return self.password_manager + + def build_session(self): + if self.session: + return self.session + + log.debug(u'Constructing opener') + + self.password_manager = self.build_password_manager() + + self.session = requests.Session() + self.session.auth = self.password_manager + + return self.session + + def send(self, body, headers=None, retries=2, timeout=30, encoding=u"utf-8"): + if not self.session: + self.session = self.build_session() + + try: + response = self.session.post(self.url, data=body, headers=headers, verify = self.verify_certificate) + response.raise_for_status() + except requests.exceptions.RequestException as err: + log.debug(err.response.content) + raise FailedExchangeException(u'Unable to connect to Exchange: %s' % err) + + log.info(u'Got response: {code}'.format(code=response.status_code)) + log.debug(u'Got response headers: {headers}'.format(headers=response.headers)) + log.debug(u'Got body: {body}'.format(body=response.text)) + + return response.text