Active Admin authentication conflicting with User

2019-02-08 18:38发布

问题:

Active Admin is a gem used for having an admin dashboard in your application. It uses Devise for logging in users and creates a separate admin_user model for the admins. My application already uses devise and has its users as the user model. Ever since I started using the active admin gem, in my routes file the following line keeps resolving to home#index and not users#dashboard even when my user is logged in. This used to work fine earlier where logged in users were taken to users#dashboard as the root url.

root :to => 'users#dashboard', :constraints => lambda {|r| r.env["warden"].authenticate? }
root :to => 'home#index'

What is happening is that the .authenticate? is checking for the admin_user (belonging to Active Admin) being logged in or not but not my user model which is what I need to check for, so when I am logged in to active admin interface, my site root becomes users#dashboard instead without checking if the user is logged in or not. How can I make .authenticate? check for the user being logged in and not admin_user ?

Any help or clues will be very much appreciated

回答1:

I was able to solve this. The issue was related to Devise expecting a single user model in the application. Here is how to fix it.

In the config/initializers/devise.rb file, add:

config.scoped_views = true

and

config.default_scope = :user #or whichever is your regular default user model

thats it, warden checks the :user for being logged in and not :admin_user



回答2:

Why are you using the get "/"? You should remove it. I'm using a definition pretty similar to yours and works fine with me. Use just:

root :to => 'users#dashboard', :constraints => lambda {|r| r.env["warden"].authenticate? }
root :to => 'home#index'


回答3:

I am not sure, but you can try something like

root :to => proc { |env| [ 302, {'Location'=> env["warden"].authenticate? ? "users/dashboard" : "/home" }, [] ] }


回答4:

What worked for me is:

constraint = lambda { |request| request.env["warden"].authenticate? and request.env['warden'].user.instance_of?(AdminUser) }