Jay*_*een 3 authorization ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)
我几乎有一个干净的石板user_policy.rb
文件,其中更新和编辑操作是默认的
def update?
false
end
def edit?
update?
end
Run Code Online (Sandbox Code Playgroud)
也许我对此的想法完全错误,应该只包装一个 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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1654 次 |
最近记录: |