Created
April 19, 2024 07:46
-
-
Save archatas/b2bec32d9f78c83854736819dedd4320 to your computer and use it in GitHub Desktop.
The @basic_authentication decorator for Django views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
from functools import wraps | |
from django.conf import settings | |
from django.http import HttpResponse | |
from django.utils.encoding import force_str | |
def basic_authentication(function): | |
@wraps(function) | |
def wrap(request, *args, **kwargs): | |
authorization_passed = False | |
if "HTTP_AUTHORIZATION" in request.META: | |
auth = request.META["HTTP_AUTHORIZATION"].split() | |
if len(auth) == 2: | |
if auth[0].lower() == "basic": | |
username, password = force_str(base64.b64decode(auth[1])).split(":") | |
if ( | |
username == settings.BASIC_AUTHENTICATION_USERNAME | |
and password == settings.BASIC_AUTHENTICATION_PASSWORD | |
): | |
authorization_passed = True | |
if not authorization_passed: | |
response = HttpResponse() | |
response.status_code = 401 | |
response["WWW-Authenticate"] = 'Basic realm="Django Website"' | |
return response | |
response = function(request, *args, **kwargs) | |
return response | |
return wrap |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment