[英]CanCanCan: authorize/unauthorize specific model attributes
我一直在擺弄CanCanCan gem來限制普通用戶的操作,但是到目前為止,我只設法將授權限制在整個模型上,而我真正需要的是限制對某些屬性的訪問。
例如,在我的用戶模型上,除了用戶/密碼/電子郵件之外,我還有一個admin布爾值,用於驗證登錄用戶的狀態,在這種情況下,如果使用user.admin ?,它可以訪問/管理。一切,否則,它應該能夠讀取所有內容,並且只有在user.id匹配時才能更新其自己的記錄。
我已經閱讀了很多遍文檔,最近的一次是將其添加到app / models / ability.rb中。
can :update, :users, [:name, :password, :email]
這什么都沒做。
所以,
問題:用戶可以:update整個模型,也可以:read,我不能將其設置為:update或:read特定屬性。
我需要的是:用戶僅可以:edit特定屬性。
問題:限制屬性的正確語法是什么? 我必須在其他一些文件上設置其他配置嗎?
我的Ability.rb文件:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.admin?
can :manage, :all
can :import, [User, Enclosure, Blade, Component]
else
can :access, :rails_admin
can :dashboard
can :read, :all
can :history, :all
# Allows user to only edit an enclosure, if it's allocated to itself, or not allocated at all
can :update, Enclosure do |enclosure|
can :update, Enclosure if (enclosure.allocated_to == user.email && enclosure.allocation == true) || enclosure.allocation == false
end
end
end
end
我正在使用的寶石(除了默認的Rails 4寶石):
# Administration Panel Gems
gem 'rails_admin' # Rails Administration Panel Gem
gem 'rails_admin_history_rollback' # Enables users to visualize and revert history
gem 'rails_admin_import', "~> 1.0.0" # Enables importing
gem 'devise' # Authentication Gem
gem 'cancancan' # Authorization Gem
gem 'paper_trail', '~> 4.0.0.rc' # Auditing Gem (History)
謝謝!
我認為您應該使用強參數 。 該gem可讓您選擇要更新的參數。 如果您使用的是Rails 4,則gem已安裝,否則可以安裝 。
class UsersController < ApplicationController
load_and_authorize_resource
def update
if @user.update_attributes(update_params)
# hurray
else
render :edit
end
end
private
def update_params
if current_user.admin?
params.require(:user).permit(:user, :email, :password, :admin)
else
params.require(:user).permit(:user, :email, :password)
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.