How to limit access to active admin to admin users

前端 未结 2 709
攒了一身酷
攒了一身酷 2021-01-30 14:38

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?

相关标签:
2条回答
  • 2021-01-30 15:11

    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
    
    0 讨论(0)
  • 2021-01-30 15:20

    For "Normal" users you should write separate logic to login to the site or maybe I did not understand why you want to allow users to login through the active admin. Active admin using devise, just create another model called User.

    0 讨论(0)
提交回复
热议问题