自己的中间件,用于限制用户Django

时间:2019-01-03 11:57:23

标签: django django-models django-forms django-templates django-views

我要编写一个包含以下字段示例的模型。 user_idrole_idcompany_idfunctionality_idhas_access。我想编写中间件,其中用户将是raised NOT ACCESS,其中字段has_accessfalse。请帮助我该怎么做,由于我的依赖性,我无法使用内置权限。我创建了middleware.py,并遵循了官方文档。这只是我编写中间件的开始

class ACLMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response

我找到了对此代码的一些引用,但我不知道这样做是否正确,因为我使用的是django 2.1版本

from django.core.urlresolvers import reverse
from django.http import Http404

    class RestrictStaffToAdminMiddleware(object):
        """
        A middleware that restricts staff members access to administration panels.
        """
        def process_request(self, request):
            if request.path.startswith(reverse('admin:index')):
                if request.user.is_authenticated():
                    if not request.user.is_staff:
                        raise Http404
                else:
                    raise Http404

2 个答案:

答案 0 :(得分:0)

在调用__call__之前,应将所需的检查放入中间件的self.get_response方法中。可能看起来像这样

def __call__(self, request):
    if not request.user.has_access:
        raise PermissionDenied

    response = self.get_response(request)

    # Code to be executed for each request/response after
    # the view is called.

    return response

答案 1 :(得分:0)

您的类RestrictStaffToAdminMiddleware用于已弃用MIDDLEWARE_CLASSES的Django <1.10。在Django> = 1.10中,它仍然支持旧版本,您也可以使用MiddlewareMixin来使您的中间件兼容。

我在下面的课程适用于MIDDLEWARE Django> 1.10,用于在Staff尝试访问管理页面时从管理委员会限制用户is_staff

  • Django> = 1.10
  • Python 3.6.8

Django文档:https://docs.djangoproject.com/en/1.11/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware

from django.core.urlresolvers import reverse
from django.http import Http404

# middleware.py
class RestrictStaffFromAdminMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.user.is_authenticated():
            if request.path.startswith(reverse('admin:index')):
                if request.user.is_staff and not request.user.is_superuser:
                    raise Http404

        response = self.get_response(request)
        return response

    def process_exception(self, request, exception):
        return HttpResponse("in exception")