How to limit access to active admin to admin users

Jasper Kennis picture Jasper Kennis · Feb 23, 2012 · Viewed 9.7k times · Source

I want that only my users who have their attribute is_admin set to true to be able to access my active admin backend

how should I do this?

"Normal" users should only be able to login to the site, not to active admin.

Answer

alony picture alony · Feb 23, 2012

In config/initializers/active_admin.rb you have such config:

config.authentication_method = :authenticate_admin_user!

so if you create a method named authenticate_admin_user! in the ApplicationController, then ActiveAdmin will check if the user can go to the admin pages or not. Like this:

# restrict access to admin module for non-admin users
def authenticate_admin_user!
  raise SecurityError unless current_user.try(:admin?)
end

and rescue from that exception in ApplicationController (or you can actually redirect inside the authenticate_admin_user! method)

rescue_from SecurityError do |exception|
  redirect_to root_url
end

And one more small thing, if you don't have admin_users, then it would be nice to change this line in config/initializers/active_admin.rb:

config.current_user_method = :current_user

And with devise you might want to make the default path different for admin/non-admin users, so you can define after_sign_in_path_for method in the controller

# path for redirection after user sign_in, depending on user role
def after_sign_in_path_for(user)
  user.admin? ? admin_dashboard_path : root_path 
end