限制特定用户/客户的页面视图访问
我认为这当然不是一个新问题,但事情是这样的:
在我基于 Django 的订单系统中,每个用户(不是员工)都与一个 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")
必须是一个更好/更简单的方法来处理这个问题 - 有什么想法吗?
干杯
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的发票模型中添加一个名为 user: 的字段,
然后像这样检索特定用户的记录:
使用反向关系检索给定用户的发票就变得很简单:
另外,请查看 @login_required 装饰器。
Add a field to your invoice model called user:
then retrieve records for a specific user like this:
Retrieving invoices for a given user is then trivial with the reverse relation:
Also, look at the @login_required decorator.
我建议为您的客户模型制定一些业务逻辑。 这样,您就可以拥有一个
get_invoices()
方法,该方法仅返回该客户的发票列表。 此方法依次调用 is_authenticated() 方法,以确保当前状态允许检索受保护的客户数据,或者引发异常。这样,无论您的代码尝试在何处获取客户的发票,如果当前状态无权访问发票,则始终会抛出异常,并且只要您使用这些方法。
I'd recommend making some business logic for your customer model. This way you could have a
get_invoices()
method that returns a list of invoices for that customer only. This method in turn would call ais_authenticated()
method that ensures that the current state allows retrieval of protected customer data, or raises an exception.With this, no matter where your code tries to get invoices for a customer, an exception will always be thrown if the current state does not have access to the invoices, and you won't have to worry about inconsistent behavior as long as you use these methods.