【问题标题】:Restrict page view access to specific users/customers限制特定用户/客户的页面查看访问权限
【发布时间】:2010-11-01 19:44:47
【问题描述】:

我认为这当然不是一个新问题,但它是这样的:

在我基于 Django 的 Order 系统中,每个用户(不是员工)都与一个 CustomerProfile 对象相关,该对象将该用户与正确的 Customer 对象匹配。此客户用户可以登录并查看未结发票。要查看客户的发票,请导航至以下内容:

/invoices/customer/97/

(客户发票 #97)

这很好,但我需要加入一些身份验证,以便作为客户个人资料一部分的用户无法通过手动输入 /invoices/customer/92/ 查看其他客户的发票(例如,发票 92 属于另一个客户) .

我有这个,但它确实不是好的代码(并且不起作用):

def customer_invoice_detail(request, object_id):
    user = threadlocals.get_current_user()
    try:
        userprofile = UserProfile.objects.get(user=user)
        user_customer = userprofile.customer.id
    except UserProfile.DoesNotExist:
        user_customer = None
    if (request.user.is_authenticated() and user_customer is not null) or request.user.is_staff():
        invoice = CustomerInvoice.objects.get(pk=object_id)
        product_list = CustomerInvoiceOrder.objects.filter(invoice=object_id)
        context = {
        'object': invoice,
        'product_list': product_list,
        }
        return render_to_response("invoices/customer_invoice_detail.html", context, context_instance=RequestContext(request))
    else:
        return HttpResponse("You are not authorised to view this invoice")

必须是更好/更简单的方法来处理这个问题 - 有什么想法吗?

干杯

【问题讨论】:

    标签: django django-urls


    【解决方案1】:

    在您的发票模型中添加一个名为 user 的字段:

    user = models.ForeignKey(User, related_name="invoices")
    

    然后像这样检索特定用户的记录:

    invoice = CustomerInvoice.objects.get(pk=object_id, user=request.user)
    

    使用反向关系检索给定用户的发票是微不足道的:

    request.user.invoices.all()
    

    另外,看看@login_required 装饰器。

    【讨论】:

      【解决方案2】:

      我建议为您的客户模型制定一些业务逻辑。这样你就可以有一个get_invoices() 方法,它只返回该客户的发票列表。该方法依次调用is_authenticated() 方法,以确保当前状态允许检索受保护的客户数据,或引发异常。

      这样,无论您的代码在哪里尝试为客户获取发票,如果当前状态无法访问发票,则始终会引发异常,并且您不必担心不一致的行为只要当您使用这些方法时。

      【讨论】:

        猜你喜欢
        • 2016-10-15
        • 2023-03-29
        • 1970-01-01
        • 2014-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-03
        • 2018-07-21
        相关资源
        最近更新 更多