简体   繁体   English

如何使用CanCan能力授权控制器中的动作?

[英]How to authorise action in a controller using CanCan ability?

I'm using CanCan gem for authorisation in my Rails project. 我在我的Rails项目中使用CanCan gem进行授权。

The ability.rb file look something like: ability.rb文件如下所示:

class Ability
  include CanCan::Ability

  def initialize(user)
    @user = user || User.new
    send @user.role.name.underscore unless @user.role.nil?
  end

  private

  def partneradmin
    can :manage,  :all
    cannot :access, User, role_id: @user.role.id
    cannot :manage, Watchlist
    can :manage, Attachment
  end

end

I have another controller controllers/admin/users_controller.rb which looks like: 我还有另一个控制器controllers/admin/users_controller.rb ,它看起来像:

class Admin::UsersController < AdminController

  load_and_authorize_resource

  respond_to :html, :json

  def index
  end

  def new
  end
end

Now I want to restrict access to Admin::UsersController#index action so partneradmin user can't access the action. 现在,我想限制对Admin::UsersController#index操作的访问,以便partneradmin用户无法访问该操作。 I tried to add cannot :access, Admin::UsersController but with no luck as I can still access Admin::UsersController#index page. 我试图添加cannot :access, Admin::UsersController但是没有运气,因为我仍然可以访问Admin::UsersController#index页面。

Please note that I don't want to restrict access for all Users resources. 请注意,我不想限制所有用户资源的访问。 As for example I have PartnerAdmin::UsersController#index and I don't want to restrict it but only for Admin::UsersController#index (based on the controller and not model). 例如,我有PartnerAdmin::UsersController#index ,我不想限制它,而仅对Admin::UsersController#index (基于控制器而不是模型)进行限制。

I had to add cannot :index, AdminController so ability.rb would look: 我必须添加cannot :index, AdminController所以ability.rb看起来如下:

  def partneradmin
     can :manage,  :all
     cannot :access, User, role_id: @user.role.id
     cannot :manage, Watchlist
     can :manage, Attachment 
     cannot :index, AdminController
   end

Then to add authorize_resource :class => AdminController in the controller. 然后在控制器中添加authorize_resource :class => AdminController

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM