小编典典

使Django的login_required为默认值的最佳方法

django

我正在开发一个大型Django应用程序,其中绝大多数需要登录才能访问。这意味着我们在整个应用程序中都花了很多钱:

@login_required
def view(...):

很好,只要我们记得将它添加到任何地方,它就可以很好地工作!可悲的是,有时我们忘记了,而且失败往往不是很明显。如果到视图的唯一链接是在@login_required页面上,则你不太可能注意到实际上无需登录即可进入该视图。但是,坏人可能会注意到,这是一个问题。

我的想法是反转系统。不必在任何地方键入@login_required,而是使用类似以下内容的东西:

@public
def public_view(...):

仅用于公共物品。我试图用一些中间件来实现这一点,但似乎无法使其正常工作。我认为,我尝试的所有内容都与我们正在使用的其他中间件进行了严重的交互。接下来,我尝试编写一些内容来遍历URL模式,以检查不是@public的所有内容都被标记为@login_required-至少如果忘记了某些内容,我们将很快得到错误提示。但是后来我不知道如何判断@login_required是否已应用于视图…

那么,什么是正确的方法呢?谢谢你的帮助!


阅读 984

收藏
2020-03-26

共1个答案

小编典典

中间件可能是你最好的选择。我过去使用过这段代码,是在其他地方的代码段中进行了修改:

import re

from django.conf import settings
from django.contrib.auth.decorators import login_required


class RequireLoginMiddleware(object):
    """
    Middleware component that wraps the login_required decorator around
    matching URL patterns. To use, add the class to MIDDLEWARE_CLASSES and
    define LOGIN_REQUIRED_URLS and LOGIN_REQUIRED_URLS_EXCEPTIONS in your
    settings.py. For example:
    ------
    LOGIN_REQUIRED_URLS = (
        r'/topsecret/(.*)$',
    )
    LOGIN_REQUIRED_URLS_EXCEPTIONS = (
        r'/topsecret/login(.*)$',
        r'/topsecret/logout(.*)$',
    )
    ------
    LOGIN_REQUIRED_URLS is where you define URL patterns; each pattern must
    be a valid regex.

    LOGIN_REQUIRED_URLS_EXCEPTIONS is, conversely, where you explicitly
    define any exceptions (like login and logout URLs).
    """
    def __init__(self):
        self.required = tuple(re.compile(url) for url in settings.LOGIN_REQUIRED_URLS)
        self.exceptions = tuple(re.compile(url) for url in settings.LOGIN_REQUIRED_URLS_EXCEPTIONS)

    def process_view(self, request, view_func, view_args, view_kwargs):
        # No need to process URLs if user already logged in
        if request.user.is_authenticated():
            return None

        # An exception match should immediately return None
        for url in self.exceptions:
            if url.match(request.path):
                return None

        # Requests matching a restricted URL pattern are returned
        # wrapped with the login_required decorator
        for url in self.required:
            if url.match(request.path):
                return login_required(view_func)(request, *view_args, **view_kwargs)

        # Explicitly return None for all non-matching requests
        return None

然后在settings.py中,列出你要保护的基本URL:

LOGIN_REQUIRED_URLS = (
    r'/private_stuff/(.*)$',
    r'/login_required/(.*)$',
)

只要你的站点遵循要求身份验证的页面的URL约定,此模型就可以工作。如果这不是一对一的适合,你可以选择修改中间件以更紧密地适应你的情况。

我喜欢这种方法-除了消除了用@login_required修饰符乱扔代码库的必要性之外-如果身份验证方案发生更改,你还有一个地方可以进行全局更改。

2020-03-26