5
votes

I have Rails_admin installed with devise and I want to restrict the /admin dashboard to only admins. For the moment my code looks like :

config.authenticate_with do
    warden.authenticate! scope: :user
  end

config.current_user_method(&:current_user)

As you can see users can get in to the dashboard so I want only the users with a boolean true in the admin column of the user table to get access to the dashboard.

How would you suggest I do this ?

2

2 Answers

19
votes

If you dont want to use cancan you can do this:

config.authorize_with do
    redirect_to main_app.root_path unless current_user.try(:admin?)
end

I use this and it works fine.

7
votes

I would recommend you to use an authorization gem called cancancan (is the updated version of cancan) it's super easy to use and it will let you to give certain permissions to different kind of users. If you don't know nothing about this gem i will recommend you to see this railscasts that will teach you how to use it properly.

So after you installed the cancancan gem in the ability.rb file you just need to do something like this to limit the admin access

models/ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user && user.admin?
      can :access, :rails_admin       # only allow admin users to access Rails Admin
      can :dashboard           
      can :manage, :all
    else
      can :read, :all                   # allow everyone to read everything
    end
  end
end

And don't forget to tell to the rails_admin gem that you are using cancancan to validate the authorization

config/initializers/rails_admin.rb

RailsAdmin.config do |config|

  ## == Cancan ==
  config.authorize_with :cancan

end

To user the "user.admin?" method you must create it into the user model, but it will only work if you have a role model that has_many users and users belongs_to role otherwise you will need other way to verify the role, so it will be something like this

models/role.rb

has_many :users

models/user.rb

belongs_to :role

def admin?
  role_id == 0 # If you have id == 0 for admin
end

Also i will recommend you to use a role model or enum to manage the different roles with ease.

I hope it helps :D