1

我正在为用户身份验证和权限实施 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.

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


这是设置的方式:

应用控制器:

check_authorization :unless => :devise_controller? # Cancan

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

用户控制器

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

  ...
end

管理员控制器

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

能力.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

我错过了什么?

4

3 回答 3

0

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

rescue_from CanCan::AccessDenied , :with => :login_page
private
def login_page
   redirect_to login_path
end
于 2012-12-26T21:19:00.763 回答
0

您应该在没有条件的情况下将“controller.authorize_resource”添加到 admin/register.if 能力。

controller.authorize_resource

示例:可以:管理,:所有

如果有条件,

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 => each_branch.id

我希望它对你有帮助

于 2012-12-26T21:19:18.660 回答
0

我的 Admins Controller 不是 < ApplicationController,因此它没有加载 ApplicationController rescue_from 方法。

进行更改解决了我的问题。

于 2012-12-26T22:27:15.937 回答