Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django staff login to all urls

I want to define some specific urls starts with /staff/* to access only by staff. So only staffs can access the urls starts with /staff/*

How can I define that in Django ?

like image 966
Karesh A Avatar asked Dec 24 '22 00:12

Karesh A


2 Answers

You can use user_passes_test or staff_member_required decorator for the view that you associate with your url (that starts with /staff/), an example might be as follows:

With user_passes_test decorator:

from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_staff, login_url='/some_url/')
def your_view(request, ...):
    # Only for staff

With staff_member_required decorator:

from django.contrib.admin.views.decorators import staff_member_required

@staff_member_required
def your_view(request, ...):
    # Only for staff
like image 158
ettanany Avatar answered Dec 26 '22 12:12

ettanany


Use a custom middleware. If the url starts with /staff/ and request.user is not staff, raise Http404 or return some special message to client.

Below is an example:

For django version < 1.10:

class StaffCheckMiddleware(object):
    def process_request(self, request):
        full_path = request.get_full_path()
        if full_path.startswith('/staff/') and not request.user.is_staff:
            raise Http404      

For django version 1.10 or above:

class StaffCheckMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        full_path = request.get_full_path()
        if full_path.startswith('/staff/') and not request.user.is_staff:
            raise Http404

        response = self.get_response(request)
        return response

Then add StaffCheckMiddleware in settings.py.

like image 38
Han He Avatar answered Dec 26 '22 12:12

Han He