From 693cb098a7bc8fbff5fb97c1ac031d0b6e397060 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dariusz=20G=C3=B3recki?= Date: Thu, 11 Aug 2016 12:04:28 +0100 Subject: Add this feature to chenges & small improvement --- CHANGES.txt | 5 +++++ pyramid/authentication.py | 13 +++++++++++-- pyramid/tests/test_authentication.py | 12 ++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 8cb4c602e..a614a4499 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -17,6 +17,11 @@ Backward Incompatibilities Features -------- +- The `_get_credentials` private method of `BasicAuthAuthenticationPolicy` + has been extracted into standalone function `extract_http_basic_credentials` + in `pyramid.authentication` module, this function extracts HTTP Basic + credentials from `request` object, and returns them as a named tuple. + Bug Fixes --------- diff --git a/pyramid/authentication.py b/pyramid/authentication.py index 46909d84e..034da9e46 100644 --- a/pyramid/authentication.py +++ b/pyramid/authentication.py @@ -1,6 +1,7 @@ import binascii from codecs import utf_8_decode from codecs import utf_8_encode +from collections import namedtuple import hashlib import base64 import re @@ -1118,9 +1119,16 @@ class _SimpleSerializer(object): return bytes_(appstruct) +http_basic_credentials = namedtuple('http_basic_credentials', + ['username', 'password']) + + def extract_http_basic_credentials(request): """ A helper function for extraction of HTTP Basic credentials - from a given :term:`request`. + from a given :term:`request`. Returned values: + + - ``None`` - when credentials couldn't be extracted + - ``namedtuple`` with extracted ``username`` and ``password`` attributes ``request`` The :term:`request` object @@ -1153,4 +1161,5 @@ def extract_http_basic_credentials(request): username, password = auth.split(':', 1) except ValueError: # not enough values to unpack return None - return username, password + + return http_basic_credentials(username, password) diff --git a/pyramid/tests/test_authentication.py b/pyramid/tests/test_authentication.py index 53747b6f0..32923c9ab 100644 --- a/pyramid/tests/test_authentication.py +++ b/pyramid/tests/test_authentication.py @@ -1536,6 +1536,18 @@ class TestExtractHTTPBasicCredentials(unittest.TestCase): b'm\xc3\xb6rk\xc3\xb6password'.decode('utf-8') )) + def test_namedtuple_return(self): + import base64 + request = testing.DummyRequest() + request.headers['Authorization'] = 'Basic %s' % base64.b64encode( + bytes_('chrisr:pass')).decode('ascii') + fn = self._get_func() + result = fn(request) + + self.assertEqual(result.username, 'chrisr') + self.assertEqual(result.password, 'pass') + + class TestSimpleSerializer(unittest.TestCase): def _makeOne(self): -- cgit v1.2.3