当我尝试导航到/admin 时。 Cancancan 如果没有用户登录并且有非管理员用户登录,则会引发执行。我想被重定向到登录屏幕 - 如果登录成功,请进入rails_admin仪表板。
请参阅下面的我当前的代码/配置,如果您需要更多信息,请告诉我:
/app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user && user.admin?
can :access, :rails_admin # only allow admin users to access Rails Admin
can :dashboard
can :manage, :all
else
can :read, :all # allow everyone to read everything
end
end
end
/config/initializers/rails_admin.rb
RailsAdmin.config do |config|
### Popular gems integration
# == Devise ==
# config.authenticate_with do
# warden.authenticate! scope: :user
# end
# config.current_user_method(&:current_user)
# == Cancan ==
config.authorize_with :cancan
## == Pundit ==
# config.authorize_with :pundit
## == PaperTrail ==
# config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0
### More at https://github.com/sferik/rails_admin/wiki/Base-configuration
config.actions do
dashboard # mandatory
index # mandatory
new
export
bulk_delete
show
edit
delete
show_in_app
## With an audit adapter, you can add:
# history_index
# history_show
end
config.model 'User' do
create do
field :name
field :email
field :password
field :password_confirmation
field :role
end
edit do
field :name
field :email
field :password
field :password_confirmation
field :role
end
end
end
/config/routes.rb
Rails.application.routes.draw do
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
# authenticate :admin do
# mount RailsAdmin::Engine => '/admin', as: :rails_admin
# end
root to: 'visitors#index'
devise_for :users
resources :users
devise_scope :user do
get "signup", to: "devise/registrations#new"
get "login", to: "devise/sessions#new"
get "logout", to: "devise/sessions#destroy", as: 'logout'
end
end
听起来你正在寻找从CanCan::AccessDenden例外中拯救出来。
rescue_from CanCan::AccessDenied do |exception|
redirect_to login_path, :alert => exception.message
end
将login_path
替换为登录名的实际路径名。您可以通过执行rake routes
并找到指向devise/sessions#new
的条目来找到它
您还可以使逻辑更加健壮,并且仅在他们尝试访问管理区域中的页面时才重定向。
我有类似的情况,我能够将没有管理员重定向到根路径。我正在使用Rails 5
和Ruby 2.3
这是我的设置:
管理导轨
# config/initialize/rails_admin.rb
config.authorize_with do
unless current_user.try(:admin?)
flash[:error] = "You are not authorize to access this page!"
redirect_to main_app.root_path
end
end
灿灿
# models/ability.rb
def initialize(user)
user ||= User.new # guest user (not logged in)
can :manage, :all if user.role == "user"
end
当用户尝试访问/admin
时,它会重定向到根路径,并显示闪存错误。