【问题标题】:Russian Doll caching and hiding sensitive links俄罗斯娃娃缓存和隐藏敏感链接
【发布时间】:2015-02-08 04:52:52
【问题描述】:

我们如何在缓存视图时隐藏敏感的或用户特定的链接,例如“编辑”或“删除”按钮?

在使用缓存的时候,不能真正使用条件句,比如:

<% if current_user.can? edit %>
  <%= link_to 'Edit', edit_post_path(@post) %>
<% end %>

因为所有查看者都会看到相同的页面。

一些教程告诉我,我可以这样使用 CSS:

<% if current_user.can? edit %>
  <%= link_to 'Edit', edit_post_path(@post), class: 'admin-link' %>
<% end %>

但我将如何验证编辑权限?

【问题讨论】:

    标签: ruby-on-rails caching


    【解决方案1】:

    您可以在缓存键中添加该部分,例如

    <% cache [@post, current_user.can? :edit] do %>
      <% if current_user.can? edit %>
         <%= link_to 'Edit', edit_post_path(@post) %>
      <% end %>
    <% end %>
    

    只需确保处理用户未登录的部分,例如,您可以将其发送到控制器的变量中

    @can_edit = user_signed_in? && current_user.can? :edit
    

    那么在视图中它会变成

    <% cache [@post, @can_edit] do %>
    

    这样,rails 将生成两个缓存,一个用于可以编辑的用户,一个用于不能编辑的用户,并为正确的用户呈现每个缓存。

    【讨论】:

    • 这似乎是最佳做法。你能告诉我你会如何使用 CSS 来做同样的事情吗,就像在原来的问题中一样?
    • 我不确定css类如何处理它,它唯一能做的就是隐藏链接,但它仍然在html代码中,也许如果你链接到你有这个想法的地方,我也许可以提供帮助。
    • 不幸的是,该链接需要付费订阅。我猜我可以使用 JS 来检查用户权限并动态更新 HTML 类。但与你的方法相比,这似乎有点脆弱。
    猜你喜欢
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    相关资源
    最近更新 更多