繁体   English   中英

Django 装饰器,如果用户访问未经授权的页面,将用户重定向到 404?

[英]Django decorator, redirect user to 404 if they access unauthorized page?

我已经使用users_passes_test创建了一个装饰器,它工作得很好,但我的要求如下,

如果用户未通过身份验证:

然后需要将用户重定向到登录页面

否则,如果用户已通过身份验证但无权访问该页面:

然后他们需要被重定向到404页面

如何根据上述需要修改我的装饰器?

from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth import REDIRECT_FIELD_NAME


def is_student(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    actual_decorator = user_passes_test(
        lambda u: (u.is_authenticated and u.role == 'student'),
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator

这是我的装饰师,请帮忙!

为简单起见,您可以选择堆叠装饰器@login_required@user_passes_test ,然后定义它们各自的重定向 URL:

@login_required(login_url='/login/')
@user_passes_test(lambda user: user.role == 'student', login_url='/notfound/')
def my_view(request):
    ...

或者重用一个普通的装饰器:

from functools import partial


def is_student(function=None, redirect_field_name=None, login_url=None, notfound_url=None):
    if function is None:
        # Handle @is_student which translates to is_student(some_view) and @is_student(...) which translates to is_student(...)(some_view). The first will automatically pass the function while the second would call the response of this decorator (the partial function below) and pass the function.
        return partial(is_student, redirect_field_name=redirect_field_name, login_url=login_url, notfound_url=notfound_url)

    decorators = [
        login_required(login_url=login_url),
        user_passes_test(lambda user: user.role == 'student', login_url=notfound_url),
    ]

    decorated_func = function
    for decorator in reversed(decorators):
        decorated_func = decorator(decorated_func)

    return decorated_func


@is_student(redirect_field_name="next", login_url="/login/", notfound_url="/notfound/")
def some_view(request, ...):
    ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM