简体   繁体   English

如何使用urls.py自定义django auth装饰器?

[英]How to customize django auth decorator with urls.py?

I have several urls defined: 我定义了几个网址:

url(r'^board/$', TemplateView.as_view(template_name='recruit/board.html'), name='recruit_board'),
url(r'^job/$', login_required(TemplateView.as_view(template_name='recruit/job_detail.html')), name='job_detail'),
url(r'^company/$', login_required(TemplateView.as_view(template_name='recruit/company_detail.html')), name='company_detail'),

... and users I designed have two account types: A or B . ...并且我设计的用户有两种帐户类型: AB。

The "job" url can only be accessed by users with an A account type, and the "company" url can only be viewed by B account type users. 只有具有A帐户类型的用户才能访问“工作” URL,而只有B帐户类型的用户才能访问“公司” URL。 If users try to access a wrong url, it will be redirected to the "board" url. 如果用户尝试访问错误的URL,它将被重定向到“ board” URL。

I have used the login_required decorator, and I know about user_passes_test , but I don't know how to go on from here. 我使用过login_required装饰器,并且我对user_passes_test有所了解,但是我不知道如何从这里继续。 Can I write a new decorator that works just like login_required and get what I want? 我可以编写一个与login_required一样工作的新装饰器,得到我想要的吗?

I think group_required decorator is match for your purpose. 我认为group_required装饰器与您的目的相匹配。

I assume you have three group ['admin', 'job', 'company'] , you can write the code like this. 我假设您有三组['admin', 'job', 'company'] ,您可以编写如下代码。 Since group_required has checked is_authenticated , you do not need login_required anymore. 由于group_required已检查is_authenticated ,因此您不再需要login_required

from django.conf.urls import url
from django.views.generic import TemplateView
from django.contrib.auth.decorators import user_passes_test

def group_required(*group_names):
    """Requires user membership in at least one of the groups passed in."""
    def in_groups(u):
        if u.is_authenticated():
            if bool(u.groups.filter(name__in=group_names)) | u.is_superuser:
                return True
        return False
    return user_passes_test(in_groups)

url(r'^board/$', TemplateView.as_view(template_name='recruit/board.html'), name='recruit_board'),
url(r'^job/$', group_required(['admin', 'job'])(TemplateView.as_view(template_name='recruit/job_detail.html')), name='job_detail'),
url(r'^company/$', group_required(['admin', 'company'])(TemplateView.as_view(template_name='recruit/company_detail.html')), name='company_detail'),

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

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