Django 中特定路由的自定义身份验证中间件

问题描述 投票:0回答:2

我为 Django 项目实现了自定义身份验证设置。用户有一些用户角色。现在我想确保某些特定的路由只能被特定的用户角色接受。假设只有具有

edit/uploaded-files
的用户才能接受
role = 1
。所以我为此创建了一个中间件。

from django.shortcuts import redirect

class HRMiddleware(object):
    def process_request(self, request):
        user = request.user
        if not (user and user.is_authenticated() and user.email):
            return redirect('')
        if user.role_id.id != 1:
            raise 403
        return None

现在我如何才能将此中间件仅应用于某些特定路线? 我找到了一些解决方案,例如使用装饰器

@decorator_from_middleware(MyMiddleware)
并在中间件中指定路由。有没有更好的方法来做到这一点?实际上我是一名 Laravel 开发者。这是我的第一个 Django 项目。在 Laravel 中我们可以在路由中指定中间件。请帮助我

python python-3.x django django-middleware
2个回答
1
投票

试试这个:

URLS = ['/some_path/']

class HRMiddleware(object):
    def process_request(self, request):
        user = request.user
        if not (user and user.is_authenticated() and user.email) and request.path in URLS:
            return redirect('')
        if user.role_id.id != 1:
            raise 403
        return None

0
投票

我认为这要好得多

from django.http import Http404

URLS = ['/仪表板/']

HRM中间件类: def init(self, get_response): self.get_response = get_response def call(自我,请求): 用户=请求.用户 响应 = self.get_response(请求) 如果不是(user 和 user.is_authenticated 和 user.email)和 URL 中的 request.path: 引发Http404 返回回复

© www.soinside.com 2019 - 2024. All rights reserved.