无法使用CanCan和Authlogic进行授权

时间:2011-05-17 16:29:17

标签: ruby-on-rails-3 authlogic roles cancan

我正在尝试使用Authlogic实现角色,以限制我的rails应用程序中的控制器访问。只要我使用load_and_authorize和filter_resource_access实现它,我就无法以任何角色访问控制器。
在我的用户模型中,我有一个角色字段,其中has_many roles_users指向Roles模型。因此,用户1是“管理员”,具有角色分配1,其链接到角色1,即“管理员”。

ability.rb

include CanCan::Ability

def initialize(user)
 user ||= User.new # guest user
 can :read, InstallQuote
 can :create, InstallQuote
 if user.role? :admin
  can :manage, :all
 end

application_controller.rb

helper :all
protect_from_forgery # See ActionController::RequestForgeryProtection for details
helper_method :current_user_session, :current_user  

rescue_from CanCan::AccessDenied do |exception|
 flash[:error] = exception.message
   redirect_back_or_default(root_path)
 end

before_filter { |c| Authorization.current_user = c.current_user }
filter_parameter_logging :password, :password_confirmation 

protected
  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.user
end

clients_controller.rb

class ClientsController < ApplicationController
# before_filter :authenticate, :only => [:edit, :update, :show, :index]

load_and_authorize_resource # For declarative authorization
filter_resource_access

# belongs_to :company
# before_filter :require_user, :only => [:edit, :update, :index, :destroy]
# before_filter :admin_user, :only => :destroy
helper_method :sort_column, :sort_direction
before_filter :correct_user, :only => [:edit, :update, :show, :index]

user.rb

acts_as_authentic
has_many :roles_users
has_many :roles, :through => :roles_users
before_create :setup_role
attr_accessible :email, :login, :first_name, :last_name, :role_id, :password, :password_confirmation, :active

(我已经注释掉了我不想抛弃的旧代码。)

任何人都知道我缺少什么?

1 个答案:

答案 0 :(得分:0)

确保您已登录,user.role? :admin返回true。

如果不是原因,您可以直接在控制台中调试:

user = User.first
ability = Ability.new(user)
ability.can? :read, Client