Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my rails application website visitors can sign up and create content. It uses devise with user model and everything works well.

Now I want to use rails_admin for managing website resources and users etc and only people with administrative previllages should be able to access it.

Should I create a separate AdminUser model for admin panel access or use User model with role of admin, and use some authorization library to manage access.

If I user only one model then I want users to be redirected to admin panel after signin if user is admin and if not then I want user to be redirected to their profile. And which authorization library cancan or pundit will be more suitable in my case.

Thanks!

like image 446
lightsaber Avatar asked Nov 24 '14 10:11

lightsaber


1 Answers

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.

like image 107
monkbroc Avatar answered Oct 18 '22 15:10

monkbroc