-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add view for togging Django maintenance mode
- Loading branch information
Showing
4 changed files
with
69 additions
and
1 deletion.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import base64 | ||
import binascii | ||
|
||
from django.contrib.auth import authenticate | ||
from django.http import JsonResponse | ||
from django.utils.deprecation import MiddlewareMixin | ||
from django.utils.encoding import smart_str | ||
|
||
|
||
class BasicAuthenticationMiddleware(MiddlewareMixin): | ||
@staticmethod | ||
def process_request(request): | ||
if "HTTP_AUTHORIZATION" in request.META: | ||
auth_parts = request.META.get("HTTP_AUTHORIZATION", "").split() | ||
auth_error = "Unauthorized" | ||
|
||
if not auth_parts or len(auth_parts) != 2 or auth_parts[0].lower() != "basic": | ||
return JsonResponse({"error": "Unauthorized"}, status=401) | ||
else: | ||
username_password = smart_str(auth_parts[1]) | ||
try: | ||
username_password = base64.b64decode(username_password).decode("utf8") | ||
username, password = username_password.split(":", 1) | ||
user = authenticate(request, username=username, password=password) | ||
except binascii.Error: | ||
auth_error = ( | ||
"Invalid basic header: Username and password must be base64 encoded with a colon delimiter " | ||
"(e.g. 'username:password')." | ||
) | ||
user = None | ||
|
||
if user is not None: | ||
request.user = user | ||
else: | ||
return JsonResponse({"error": auth_error}, status=401) |
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
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
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