Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise before_filter authenticate_admin?

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
like image 312
Martin Petrov Avatar asked Sep 14 '11 05:09

Martin Petrov


2 Answers

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.

like image 136
Michael De Silva Avatar answered Nov 09 '22 01:11

Michael De Silva


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!

like image 29
Micah Bales Avatar answered Nov 09 '22 03:11

Micah Bales