我正在为用户身份验证和权限实施 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
我错过了什么?