Rails_admin: Should I have admin_user or user with admin role to manage users and admin panel

主宰稳场 提交于 2019-12-04 06:21:33
monkbroc

Good question. I use Rails Admin and Pundit in my project.

I prefer having an Admin model separate from the User model.

One reason is that I like to be able to "Become a user" from Rails Admin to be able to help them when they have an issue. Its easier to do when you have separate User and Admin models.

The Admin model can be super simple. Generate it with rails generate devise Admin

Then in your config/initializers/rails_admin.rb add

config.authenticate_with do
  warden.authenticate! :scope => :admin
end

config.current_user_method(&:current_admin)

To redirect to the correct profile, add this method to your ApplicationController

def after_sign_in_path_for(resource)
  if resource.class == Administrator
    rails_admin_path
  else
    # Change profile_path to where you want regular users to go
    stored_location_for(resource) || profile_path
  end
end

In order to prevent signing out from the current Admin when signing out from the current User, set this configuration in config/initializers/devise.rb

config.sign_out_all_scopes = false

To address your other question, I have used both CanCan and Pundit. I like Pundit better because with CanCan all the permissions are evaluated for each request. With Pundit, permissions are only checked when needed. Pundit is also more flexible in my experience.

Dieglock

Complementing monkbroc answer:

For me, at RoR 4, variables :admin and :current_admin never worked. Saw some pages about the problem, is Warden not registering the role when at Devise is not a model but a enum... and found another solution like this:

config.authorize_with do |controller|
  unless current_user.try(:admin?)
   flash[:error] = "You are not an admin"
   redirect_to 'visitors#index'
 end
end

The code comes from this other answer: Authenticate using Devise and Rails Admin for particular routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!