我要编写一个包含以下字段示例的模型。 user_id
,role_id
,company_id
,functionality_id
,has_access
。我想编写中间件,其中用户将是raised NOT ACCESS
,其中字段has_access
是false
。请帮助我该怎么做,由于我的依赖性,我无法使用内置权限。我创建了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
答案 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
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")