From d2fd3b17701bd37324255f75ba979a02bc906907 Mon Sep 17 00:00:00 2001 From: Raymond Penners Date: Sun, 4 Mar 2018 19:58:10 +0100 Subject: [PATCH] feat: Support Basic Authentication for show details --- README.rst | 5 +++++ healthpoint/views.py | 21 +++++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 1ea5ed1..ad23e0f 100644 --- a/README.rst +++ b/README.rst @@ -35,6 +35,11 @@ Install the app:: 'healthpoint' ] + # If specified, this user is able to see the details for each + # individual check in the endpoint. + HEALTHPOINT_BASICAUTH_USERNAME = 'john' + HEALTHPOINT_BASICAUTH_PASSWORD = 'doe' + # urls.py urlpatterns = [ ... diff --git a/healthpoint/views.py b/healthpoint/views.py index b2a8a12..a33443a 100644 --- a/healthpoint/views.py +++ b/healthpoint/views.py @@ -1,8 +1,26 @@ +from django.conf import settings from django.http import JsonResponse from healthpoint.registry import get_health_checks +def _show_health_details(request): + # Only staff members are allowed to see details... + user = getattr(request, 'user', None) + if user is not None and (user.is_staff or user.is_superuser): + return True + ba_username = getattr(settings, 'HEALTHPOINT_BASICAUTH_USERNAME', None) + ba_password = getattr(settings, 'HEALTHPOINT_BASICAUTH_PASSWORD', None) + authorization = request.META.get('HTTP_AUTHORIZATION') + if ba_username and ba_password and authorization: + method, _, auth = authorization.partition(' ') + if method.lower() == 'basic': + auth = auth.strip().decode('base64') + username, password = auth.partition(':') + return (username == ba_username and password == ba_password) + return False + + def health(request): data = {'success': {}, 'error': {}} status = 200 @@ -15,7 +33,6 @@ def health(request): if not success: status = 500 # Only staff members are allowed to see details... - user = getattr(request, 'user', None) - if user is None or not user.is_staff or not user.is_superuser: + if not _show_health_details(request): data = {} return JsonResponse(data, status=status)