0

我有一个关于 Django 和授权的小问题。我有一个应用程序,必须通过某种组织中的用户访问。例如:如果用户在组织类型 1 中,他可以,否则,他不能。

我应该使用权限还是使用自定义中间件?

4

1 回答 1

0

Use user_passes_test decorator to do it.

from django.contrib.auth.decorators import login_required,user_passes_test
def is_auth(u):
    #u is the request.user
    if user_auth_for_page(u):
            return True
    return False

def user_auth_for_page(u):
    #your Authentication function here
    #if user is in org1 return true

@user_passes_test(lambda u: is_auth(u),login_url='/home/')
@login_required
def page(request):
    ...

Again, the best approach would be to use it in conjuction with the django groups.

def is_auth(u,g):
    l=u.groups.all()
    for i in l:
        if i.name==g:
            return True
    return False
@user_passes_test(lambda u: is_auth(u,'admin'),login_url='/home/')
于 2013-05-13T16:29:07.517 回答