Reputation: 231
I've been trying to set up rails_admin and to work with Rails 4.0.4, but unfortunately I ran across some issues. I have a devise generated User model with admin added as boolean afterwards. But even if the User is admin and needs to access the rails_admin panel, I get unauthorized access. It's like the current user cannot be passed in the ability.rb properly. Not sure if this is a Rails 4 issue or I'm doing something wrong.
Here's the code, with a little (ugly?) workaround that works, but I need a more elegant solution. Thanks.
ability.rb
class Ability
include CanCan::Ability
def initialize(user)
# Define abilities for the passed in user here. For example:
#
user = User.current # guest user (not logged in)
if user.admin?
can :manage, :all
can :access, :rails_admin # needed to access RailsAdmin
can :dashboard # dashboard access
else
can :read, :all
end
end
end
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
def self.current
Thread.current[:user]
end
def self.current=(user)
Thread.current[:user] = user
end
end
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_filter :set_current_user
def set_current_user
User.current = current_user
end
end
And, of course, I have this in rails_admin.rb enabled.
RailsAdmin.config do |config|
config.authorize_with :cancan
end
Thanks!
Upvotes: 1
Views: 2463
Reputation: 231
Seems it works, but you first need a Devise model before adding rails_admin.
Also, this needs to be enabled in rails_admin initializer:
config.current_user_method(&:current_user)
Upvotes: 4
Reputation: 23268
Two things which I notice, which are strange (not sure whether any of them is the core problem)
1) You don't authenticate anywhere.
You ApplicationContoller should have:
before_filter :authenticate_user!
And you do this (which I believe you don't need to do in Devise).
before_filter :set_current_user
def set_current_user
User.current = current_user
end
2) Did you try to restart your server?
I believe RailsAdmin doesn't reload automatically (you either need to hack a special hack - https://github.com/sferik/rails_admin/wiki/How-to:-Reloading-RailsAdmin-Config-Automatically or restart a server)
Upvotes: 0