2

在我的 Django 项目中,我有由 Django 的内置身份验证系统创建的各种用户。每个用户都可以创建自己的App模型实例。我想限制用户访问对象,以便用户只能查看他们创建的实例。为此,我创建了这个视图:

@login_required
def appDetail(request, app_id):
    try:
        app = App.objects.get(pk=app_id)

        # Testing if the currently logged in user is 
        # the same as the user that created the 'app':

        if request.user.id == app.user.user.id:
            if request.method == 'POST':
                form = AppForm(request.POST, instance=app)
                if form.is_valid():
                    edited_app = form.save()
                    return HttpResponseRedirect('/thanks/')
            else:
                form = AppForm(instance=app)

        # If 'app' does not belong to logged in user, redirect to 'accessdenied' page:

        else:
            return HttpResponseRedirect('/accessdenied/')
    except LeaveApp.DoesNotExist:
        raise Http404
    return render(request, 'AppDetail.html', {'form':form})

它有效,但我想知道是否有更普遍接受和/或安全的方法来做到这一点?

4

3 回答 3

2

This is called row-level permissions and it's a very common problem. See here for all the apps that solve it.

If that particular test is all you need to do, go for a custom solution like yours (though, since it's boilerplate, it's preferable to move it to a decorator). Otherwise, just use an existing app.

于 2013-04-17T06:45:15.833 回答
1

我会将表单提交放在不同的视图中并编写自定义装饰器,您也可以将其用于类似问题。我也会返回 404 而不是拒绝访问。您可能不想向用户表明您正在保护某些东西。

于 2013-04-18T10:38:17.690 回答
1

有一个名为 user_passes_test 的装饰器,它根据用户是否通过某个检查来限制对视图的访问

from django.contrib.auth.decorators import login_required, user_passes_test

@login_required
@user_passes_test(lambda user: user.username == app.user.user.id)
MyView(request):
    ...

您还可以添加一个可选参数,以便在检查失败时重定向到的 url。

从管理页面尝试这样做也很容易,但需要一些额外的步骤。

文档在这里

于 2014-08-15T14:30:14.423 回答