Python beginners try adding basic auth to Django admin

Purpose

I wanted to do basic authentication before the login screen on the Django admin page. But I didn't want to go to other pages. I don't know much about Django and python, but I think I've done it for the time being, so I'll expose it. I don't think it's the best solution, so please let me know if there is a better way.

python: 3.5.2 Django==1.11.4

It's hard to say that the result of trial and error for about two days is super simple.

yourproject/my_admin_site.py


from django.http import HttpResponse
from django.views.decorators.cache import never_cache
from django.contrib.admin.sites import site, AdminSite
import base64

class MyAdminSite(AdminSite):

    def __init__(self, name='admin'):
        super().__init__()

    def get_urls(self):
        self._registry = site._registry
        return super().get_urls()

    @never_cache
    def login(self, request, extra_context=None):
        if not self._basicAuth(request):
            return self._http401()
        return super().login(request, extra_context)

    def _basicAuth(self, request):
        if 'HTTP_AUTHORIZATION' not in request.META:
            return False
        (authscheme, base64_idpass) = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
        if authscheme.lower() != 'basic':
            return _http401()
        idpass = base64.decodestring(base64_idpass.strip().encode('ascii')).decode('ascii')
        (id_, password) = idpass.split(':', 1)
        if id_ == "foo" and password == "bar":
            return True
        else:
            return False

    def _http401(self):
        response = HttpResponse("Unauthorized", status=401)
        response['WWW-Authenticate'] = 'Basic realm="basic auth test"'

        return response


my_site = MyAdminSite()

yourproject/urls.py


from django.conf.urls import url, include
from yourproject import my_admin_site

urlpatterns = [
    #url(r'^admin/', admin.site.urls),
    url(r'^admin/', my_admin_site.my_site.urls)
]

It is like this. スクリーンショット.png

yourproject/my_admin_site.py


    def get_urls(self):
        self._registry = site._registry
        return super().get_urls()

Basic authentication can be done without this part, but without this, a sad screen appears saying that no operation can be performed when entering admin. The list of models that can be operated is registered from the outside in _register of django.contrib.admin.sites.site, so it seems that you can not pull that information if you just inherit the model? So I solved it by copying django.contrib.admin.sites.site. \ _Register to my own class self. \ _ Register. I feel like doing it. I don't like accessing the implicit private method, but it worked. Perhaps. There is no inconvenience for now.

I think it's good and bad that there is no clear difference between python, public and private.

Reference https://bitstar.jp/blog/basic%E8%AA%8D%E8%A8%BC

Recommended Posts

Python beginners try adding basic auth to Django admin
Try to calculate RPN in Python (for beginners)
Try Debian + Python 3.4 + django1.7 ...
(Python) Try to develop a web application using Django
Introduction to Python Django (2) Win
Try to understand Python self
3 Reasons Beginners to Start Python
Basic Python grammar for beginners
~ Tips for beginners to Python ③ ~
[AWS] Try adding Python library to Layer with SAM + Lambda (Python)
Try to operate Facebook with Python
Try to calculate Trace in Python
Try converting cloudmonkey CLI to python3 -1
Try adding a wall to your IFC file with IfcOpenShell python
python beginners tried to find out
Introduction to Python Django (2) Mac Edition
Try using the Python web framework Django (1)-From installation to server startup
Migrate Django applications running on Python 2.7 to Python 3.5
Try to reproduce color film with Python
Try logging in to qiita with Python
Answer to AtCoder Beginners Selection by Python3
[Django] Want to customize your admin page?
Try to operate Excel using Python (Xlwings)
10 Python errors that are common to beginners
Python amateurs try to summarize the list ①
I tried to touch Python (basic syntax)
Adding Series to columns in python pandas
[For beginners] Try web scraping with Python
[Python] Introduce UIKit3 to your Django project
Try python
How to add pre-save processing when adding objects on the Django admin site
The fastest way for beginners to master Python
Django tutorial summary for beginners by beginners ⑦ (Customize Admin)
First steps to try Google CloudVision in Python
Try to implement Oni Maitsuji Miserable in python
Try adding fisheye lens distortion to the image
Try sending Metrics to datadog via python, DogStatsD
Try to calculate a statistical problem in Python
3.14 π day, so try to output in Python
Try using django-import-export to add csv data to django
Try auto to automatically price Enums in Python 3.6
Python for super beginners Python for super beginners # Easy to get angry
Try to solve the Python class inheritance problem
Python beginners tried to code some energy drinks
Try to solve the man-machine chart with Python
Django Tutorial Summary for Beginners by Beginners (Model, Admin)
AI beginners try to make professional student bots
Try to draw a life curve with python
Memo # 3 for Python beginners to read "Detailed Python Grammar"
Try to make a "cryptanalysis" cipher with Python
Memo # 1 for Python beginners to read "Detailed Python Grammar"
Try to automatically generate Python documents with Sphinx
"Cython" Tutorial to Make Python Explosive: Basic Configuration
Memo # 2 for Python beginners to read "Detailed Python Grammar"
Python mock to try AWS IoT Device Shadow
Try to make a dihedral group with Python
What Python beginners got hooked on with Django
Memo # 7 for Python beginners to read "Detailed Python Grammar"
From 0 to Django development environment construction to basic operation
Introduction to Programming (Python) TA Tendency for beginners
Memo # 6 for Python beginners to read "Detailed Python Grammar"