12

I added an admin role to Devise by adding a admin attribute.

Could you tell me if this is the right way to create a before_filter that requires an admin user to be signed:

in any controller:

before_filter :authenticate_admin!

in application_controller

protected
  unless current_user.try(:admin?)      
    redirect_to :new_user_session_path      
  end

2 Answers 2

25

Go with this approach

  before_filter :authenticate_user!
  before_filter do 
    redirect_to new_user_session_path unless current_user && current_user.admin?
  end

This also ensures any guests are forced to sign in as well. You don't need to modify the default method to force authentication just to access the instance method admin?

def admin?
  self.admin == true
end

My approach is to create a role attribute and check its string value against a set of intended roles - it's far more flexible this way rather than having to create many boolean attributes.

2
  • 2
    No need to define admin?, if the admin column is already a Boolean then you can just call user.admin? and it will automatically return true or false without having a admin? method in user.
    – n0denine
    Commented Apr 24, 2013 at 4:00
  • Correct, however, for most of my apps I tend to store these as strings. Combine this with an authorisation layer, i.e. CanCan, and it's easy to define levels of 'admin' prowess. For a boolean column in the DB, you do not need to redefine the predicate method as I have shown above. Commented Apr 28, 2013 at 20:18
1

Looking at the answer above (by Michael De Silva), I had an issue with the code he used. He wrote the path as a symbol (:new_user_session_path), but I needed it to be a regular path helper (new_user_session_path). Until I changed this, I was getting errors, saying the path was invalid. (I am running Rails 5.)

Hope this is helpful to others!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.