4

I'm trying to install the Rails Admin Gem using Sorcery for authentication instead of Devise.

Rails admin does provide a hook that you can use to attach your own authentication method. Here is the example they provide in their docs (using warden):

config.authenticate_with do
  warden.authenticate! :scope => :admin
end
config.current_user_method { current_admin }

I'm guessing that inside the block I need to reference the before_filter that Sorcery uses to authenticate users, which would be require_login.

However, when I try that and I try to visit /admin when logged out, I get a routing error:

No route matches {:action=>"new", :controller=>"sessions"}

This probably happens because I am being redirected within the engine rather than in the main app.

How can I set this up correctly?

David Tuite
  • 22,258
  • 25
  • 106
  • 176

2 Answers2

7
# config/initializers/rails_admin.rb
RailsAdmin.config do |config|
  config.authenticate_with do
    # Use sorcery's before filter to auth users
    require_login
  end
end

# app/controllers/application_controller.rb
class ApplicationController
  # Overwrite the method sorcery calls when it
  # detects a non-authenticated request.
  def not_authenticated
    # Make sure that we reference the route from the main app.
    redirect_to main_app.login_path
  end
end

#config/initializers/rails_admin.rb
RailsAdmin.config do |config|
  ...
  config.parent_controller = 'ApplicationController'
end
Obromios
  • 15,408
  • 15
  • 72
  • 127
David Tuite
  • 22,258
  • 25
  • 106
  • 176
  • This does not work for me. I am getting this error: ```undefined local variable or method `root_path' for # – Obromios Oct 22 '18 at 06:38
  • It was because my app did not have ```config.parent_controller = 'ApplicationController'``` in the rails_admin initialisation file. I have edited the answer accordingly. – Obromios Oct 25 '18 at 04:10
0

If you use Sorcery with Cancancan gem, you should also add config.current_user_method(&:current_user) in your config/initializers/rails_admin.rb file, or you'll get the error: You are not authorized.

AMACB
  • 1,290
  • 2
  • 18
  • 26
J.Rico
  • 1
  • 2