ruby-on-rails - 授权用户在 Rails 中使用 Pundit 编辑特定字段

标签 ruby-on-rails authorization pundit

我正在我的 Rails 应用程序中运行 Pundit 以进行授权。我似乎已经掌握了这一切,但想知道如何将编辑或更新操作限制到某个字段。

例如,用户可以编辑他们的 user.first_name、user.mobile 或 user.birthday 等,但不能编辑他们的 user.role。基本上我的逻辑是,让用户编辑任何装饰性的东西,但如果它是功能性的,则不允许。

这些字段应该只能由具有“super_admin”角色的用户编辑(我在 user.rb 上使用如下方法进行了设置)。

  def super_admin?
    role == "super admin"
  end

  def account?
    role == "account"
  end

  def segment?
    role == "segment"
  end

  def sales?
    role == "sale"
  end

  def regional?
    role == "regional"
  end

  def national?
    role == "national"
  end

  def global?
    role == "global"
  end 

我几乎有一个干净的石板user_policy.rb更新和编辑操作是默认的文件
  def update?
    false
  end

  def edit?
    update?
  end

也许我对此的想法完全错误,应该只包装一个 user.super_admin?用户显示页面上的角色字段周围的 if 语句,但如果我只是为了安全而使用该策略,这感觉是错误的。

最佳答案

使用 Pundit 的 permit_attributes 助手,它在 gem 的 README 页面中描述:https://github.com/elabs/pundit

# app/policies/post_policy.rb
class PostPolicy < ApplicationPolicy
  def permitted_attributes
    if user.admin? || user.owner_of?(post)
      [:title, :body, :tag_list]
    else
      [:tag_list]
    end
  end
end

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def update
    @post = Post.find(params[:id])
    if @post.update_attributes(post_params)
      redirect_to @post
    else
      render :edit
    end
  end

  private

  def post_params
    params.require(:post).permit(policy(@post).permitted_attributes)
  end
end

关于ruby-on-rails - 授权用户在 Rails 中使用 Pundit 编辑特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29138825/

相关文章:

ruby-on-rails - 禁用 Rails 中的自动渲染

ruby-on-rails - 在 Rails 3 中路由嵌套资源

ruby-on-rails - Rails View slim 语法中的 Br 标签

c# - 跳过基于另一个过滤器 asp .net 的过滤器执行

ruby-on-rails - 在Pundit中实现范围

ruby-on-rails - 如何访问服务器端的回形针附件?

c# - 在开发过程中绕过或关闭 [Authorize(Roles ="")]?

ruby-on-rails - rails 4 + 专家 : join model authorization in has_many :through association

ruby-on-rails - Rails 5,具有命名空间资源的 Pundit

ruby-on-rails - 专家 : Custom redirection within one user action