Trent Scott
Trent Scott

Reputation: 2028

Devise: Restricting Actions to Administrators

Following the guide here, I added a boolean attribute to my database using a migration:

rails generate migration add_admin_to_user admin:boolean

I've configured my account to be an admin (admin = 1) via Rails console. I have a controller that I want to restrict access to certain actions (new, edit, create, and destroy) for administrators only.

I'll also have normal users, I just want to restrict access to these actions for admins only in this controller. Currently, I'm using the code:

before_filter :authenticate_user!, :only => [:new, :edit, :create, :destroy]

Which restricts access to registered users -- how do I take this a step further and require admins?

Upvotes: 20

Views: 9097

Answers (2)

ipd
ipd

Reputation: 5714

You will want to define your own method in the before filter and then detect whether the user is an admin or not in that method prior to calling :authenticate_user!

before_filter :custom_method, :only => [:new, :edit, :create, :destroy]

private
def custom_method
  authenticate_user!

  if current_user.admin
     return
  else
     redirect_to root_url # or whatever
  end
end

You will want to do the authenticate_user! step prior to checking the current_user variable.

ian.

Upvotes: 9

Will Ayd
Will Ayd

Reputation: 7164

you can easily implement your own before_filter to allow access to only admin users by using the .admin? method associated with your user model. for instance:

before_filter :verify_is_admin

private

def verify_is_admin
  (current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.admin?)
end

Upvotes: 34

Related Questions