cancan能力:允许站点管理员使用rolify角色create_user来创建或签署新的设计用户

时间:2015-01-06 04:05:07

标签: ruby-on-rails devise cancan rolify cancancan

对于应用程序,我正在尝试使用cancan / cancancan,devise和rolify来实现job_code样式访问。

只有拥有job_code:create_user的网站管理员才能创建新用户

以下是代码:

class RegistrationsController < Devise::RegistrationsController 
    before_filter :check_permissions, :only => [ :new, :create, :cancel ] 
    skip_before_filter :require_no_authentication 

    def check_permissions
        authorize! :create, resource
    end
end

class Ability
  include CanCan::Ability

  def initialize(user)
     alias_action :create, :read, :update, :destroy, :to => :crud

     if user.has_role? :create_user 
        can :create, User
     end

     if user.has_role? :create_annoucement
       can :create, Announcement
     end
  end
end
在routes.rb中

,我有

devise_for :users ,:controllers => { :registrations => "registrations" }, :path_names => {:sign_in => "login", :sign_out => "logout"}, :path => "account"

应用程序控制器

class ApplicationController < ActionController::Base
    # Prevent CSRF attacks by raising an exception.
    # For APIs, you may want to use :null_session instead.
    protect_from_forgery with: :exception
    before_action :authenticate_user!
    check_authorization unless: :devise_controller?
    before_filter :set_start_time if Rails.env.development?
    before_action :configure_permitted_parameters, if: :devise_controller?

    rescue_from CanCan::AccessDenied do |exception|
      #https://github.com/ryanb/cancan/wiki/Devise
        if current_user.nil?
            session[:next] = request.fullpath
            puts session[:next]
            redirect_to new_user_session_path, :alert => "You have to log in to continue."
        else
          render file: "#{Rails.root}/public/403", formats: [:html], status: 403, layout: false
        end
    end

    def set_start_time
        @start_time = Time.now.usec
    end

    def configure_permitted_parameters
            #devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:name, :email) }
        devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:first_name, :last_name, :email, :password, :password_confirmation) }
          devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password, :user_manual) }
      end

end

当我使用时,abilities.rb中的以下代码

if user.has_role? :create_user 
        can :create, :all
end

完美无缺。它带我到User sign_up页面

但是,当我有这段代码时

if user.has_role? :create_user 
   can :create, User
end

它表示拒绝访问(403页)

我很难弄明白,我应该使用什么,而不是can :create, User

中的用户

1 个答案:

答案 0 :(得分:0)

我必须添加:read:create权限才能访问新/创建操作,然后解析:read访问权限