Rails_admin with app
I have Rails_admin installed using and I want to restrict my dashboard / admin to admins only. At the moment my code looks like this:
config.authenticate_with do
warden.authenticate! scope: :user
end
config.current_user_method(&:current_user)
As you can see, users can log into the dashboard, so I want only users with boolean true in the admin column of the users table to access the dashboard.
How would you suggest me to do this?
source to share
I would recommend that you use the cancancan resolution recorder (this is an updated version of cancan), it is very easy to use and it will allow you to give specific permissions for different users. If you don't know anything about this stone, I recommend that you see this railscasts , which will teach you how to use it correctly.
So, after you have set the cancancan gem in capability.rb file, you just need to do something like this to restrict 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 the rails_admin gem that you are using cancancan to check authorization
config / initializers / rails_admin.rb
RailsAdmin.config do |config|
## == Cancan ==
config.authorize_with :cancan
end
The user "user.admin?" method, you have to create it in a custom model, but it will only work if you have a swap model that has multiple users and users belonging to a role, otherwise you will need another way to validate the role, so it would be that 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 recommend that you use a role model or enumeration to manage the different roles with ease.
Hope this helps: D
source to share