Cancan +设计rescue_from没有捕获异常

时间:2012-12-26 21:04:31

标签: ruby-on-rails ruby-on-rails-3 devise cancan

我正在实现Devise和Cancan用于用户身份验证和权限。到目前为止,一切都运行良好,但我不能在不允许用户访问特定功能时将用户重定向到登录页面。

我的测试是:

feature 'A signed in user' do
  before(:each) do
    user = FactoryGirl.create(:user)
    visit "/login"
    fill_in "user_email", :with => user.email
    fill_in "user_password", :with => "ilovebananas"
    click_button "Sign in"
  end

  scenario 'should not have access to admin dashboard' do
    visit '/admin'
    page.should have_content 'Log in'
  end
end

我得到以下失败:

Failures:
      1) A signed in user should not have access to admin dashboard
         Failure/Error: visit '/admin'
         CanCan::AccessDenied:
         You are not authorized to access this page.

要明确的是,除了重定向到登录页面之外,我的所有权限管理都按预期工作。


以下是设置方法:

的ApplicationController:

check_authorization :unless => :devise_controller? # Cancan

rescue_from CanCan::AccessDenied do |exception|
  redirect_to login_path, alert: exception.message
end

UsersController

class UsersController < ApplicationController
  load_and_authorize_resource         # Cancan
  def queue  
    ...
  end

  ...
end

AdminsController

class AdminController < ActionController::Base
  authorize_resource :class => false # Cancan, used because AdminController doesn't have an associated model
  ...
end

ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user, not logged in
    can :queue, User

    if user.has_permission? :super_admin
      can :manage, :all
    elsif user.has_permission? :network_admin

    end      
  end
end

我错过了什么?

3 个答案:

答案 0 :(得分:0)

您必须将类名作为字符串传递。试着引用它。或尝试

rescue_from CanCan::AccessDenied , :with => :login_page
private
def login_page
   redirect_to login_path
end

答案 1 :(得分:0)

你应该无条件地将“controller.authorize_resource”添加到admin / register.if能力。

controller.authorize_resource

示例:can:manage,:all

如果条件是,

controller do
  load_and_authorize_resource :except => [:update,:index, :show, :edit]
    def scoped_collection
      end_of_association_chain.accessible_by(current_ability)
  end
end

示例:can:manage,Master :: Country,:organization_branch_id =&gt; each_branch.id

我希望它可以帮到你

答案 2 :(得分:0)

我的管理员控制器不是&lt; ApplicationController,因此它没有加载ApplicationController rescue_from方法。

让改变解决了我的问题。