延长Django的认证/授权的最佳方法 [英] Best way to extend django authentication/authorization

查看:136
本文介绍了延长Django的认证/授权的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我加入了服务条款的验收要求,我们的网站和我试图找出到的 Django的认证框架。

I'm adding in a Terms of Service acceptance requirement to our site and am trying to figure out the best way to handle this within Django's authentication framework.

为简单起见,这里有一个用户配置模型:

For simplicity's sake, here's a UserProfile model:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    accepted_tos_at = models.DateTimeField(default=None, editable=False, null=True)

所以基本上我想要做的是检查 accepted_tos_at (还是在现实大于最后TOS修订日期)。如果通过了​​这个测试,然后我们通常进行身份验证,但如果是除了登录和<$ C $所有视图C> tos_display 不可访问。

So basically what I want to do is to check that accepted_tos_at is not None (or in reality greater than the date of the last TOS revision). If it passes this test then we authenticate normally, but if it is None all views except login and tos_display are inaccessible.

我就挂了您应该如何去怎么样在全球这样做呢?我宁愿不加入 user_passes_test 装饰以我的观点每一个人,我同样想避免测试在我的观点每个人此权限。必须有一个更清洁的方式。

What I'm hung up on is how should you go about doing this globally? I would rather not add in user_passes_test decorators to every one of my views and likewise I'd like to avoid testing for this permission in every one of my views. There must be a cleaner way.

推荐答案

一般来说,当你在谈论的东西,应适用于每一个观点,那么,你在谈论的中间件。在你的情况,这是比较直接的:

Generally, when you're talking about something that should apply to every view, then, you're talking about middleware. In your case, this is relatively straight-forward:

class AcceptTOSMiddleware(object):
    def process_request(request):
        login_url = reverse('login')
        tos_url = reverse('tos_display')
        if request.path not in [login_url, tos_url]:
            profile = request.user.get_profile()
            if profile.accepted_tos_at is None or \
               profile.accepted_tos_at < settings.LAST_TOS_REVISION:
                return HttpResponseRedirect(tos_url)
        return None

首先,检查请求的URL是不是在登录或TOS意见。这prevents无限循环,如果一个重定向是必要的。然后,你检查 accepted_tos_at 。我以为你只是要存储的最后修订日期为设定,所以你需要修改,​​如果你有其他的计划。如果TOS需要被接受,用户被重定向到TOS观点,否则,中间件返回这告诉Django保持处理请求是正常的。

First, this checks if the requested URL is not the login or TOS views. This prevents infinite loops if a redirect is necessary. Then, you check the accepted_tos_at. I assumed you're simply going to store the last revision date as a setting, so you'll need to modify that if you have other plans. If the TOS needs to be accepted, the user is redirected to the TOS view, otherwise, the middleware returns None which tells Django to keep processing the request as normal.

只是中间件添加到 MIDDLEWARE_CLASSES ,你是金色的。

Just add the middleware to MIDDLEWARE_CLASSES and you're golden.

这篇关于延长Django的认证/授权的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆