Skip to content

Instantly share code, notes, and snippets.

@evansd
Created February 17, 2017 10:13
Show Gist options
  • Select an option

  • Save evansd/93c4063c1f82b627ac7843eae9bafcf8 to your computer and use it in GitHub Desktop.

Select an option

Save evansd/93c4063c1f82b627ac7843eae9bafcf8 to your computer and use it in GitHub Desktop.
from django.conf import settings
from django.core.exceptions import MiddlewareNotUsed
from django.http import HttpResponse
class BasicAuthMiddleware(object):
"""
Adds HTTP Basic Authentication site-wide
Useful for protecting staging/demo environments. Additionally, sets auth details
in a cookie so they persist beyond browser close.
"""
auth_realm = 'Protected'
auth_html = (
"<html><title>Authorization Required</title>"
"<body><h1>Authorization Required</h1></body></html>")
auth_cookie_name = 'basic_auth'
auth_cookie_max_age = 60*60*24*14
def __init__(self, get_response=None):
if not getattr(settings, 'BASICAUTH_ENABLED', False):
raise MiddlewareNotUsed()
self.get_response = get_response
def __call__(self, request):
response = self.process_request(request)
if not response:
response = self.get_response(request)
return self.process_response(request, response)
def unauthorized(self):
response = HttpResponse(self.auth_html, content_type="text/html")
response['WWW-Authenticate'] = 'Basic realm="%s"' % self.auth_realm
response.status_code = 401
return response
def process_request(self, request):
authentication = request.META.get('HTTP_AUTHORIZATION', '')
auth_cookie = request.COOKIES.get(self.auth_cookie_name, '')
if not authentication:
authentication = auth_cookie
method, auth = (authentication.split(' ',1) + [''])[:2]
if method.lower() == 'basic':
username, password = (auth.strip().decode('base64').split(':', 1) + [''])[:2]
if (username == settings.BASICAUTH_USERNAME
and password == settings.BASICAUTH_PASSWORD):
if auth_cookie != authentication:
request._set_auth_cookie = authentication
return None
return self.unauthorized()
def process_response(self, request, response):
auth_cookie = getattr(request, '_set_auth_cookie', None)
if auth_cookie is not None:
response.set_cookie(self.auth_cookie_name, auth_cookie,
max_age=self.auth_cookie_max_age)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment