Gjert
Gjert

Reputation: 1067

Restricting admin urls to already authenticated superusers in Django

I've searched around for some solutions to this, but they all focus on a single admin url. However I was wondering if there is a way to restrict ALL the admin views, not the accounts to already authenticated superusers.

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('accounts.urls'))
]

What I want is

urlpatterns = [
    url(r'^admin/', is_superuser(admin.site.urls)),
    url(r'^accounts/', include('accounts.urls'))
]

Or something like this that I can do in the view

@user_passes_test(lambda u: u.is_superuser, login_url='allauth.account.views.LoginView')
def superuser_only(request, template):
    return render(request, template)

but still allows me to use admin.site.urls.

Is there a quick and elegant way to solve this? I want all users including the superuser to authenticate through accounts app.

Upvotes: 0

Views: 189

Answers (1)

arcegk
arcegk

Reputation: 1480

You could create a middleware class that checks the request.path and the user and add it to the MIDDLEWARE var in your settings.

from django.http import Http404

class SuperUserMiddleware(object):

    def process_request(self, request):
        user = request.user
        is_anonymous = user.is_anonymous()
        if 'admin' in request.path
            if not is_anonymous:
                if not user.is_superuser:
                    raise Http404
            else:
                raise Http404

Upvotes: 2

Related Questions