Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise: Restricting Actions to Administrators

Tags:

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?

like image 550
Trent Scott Avatar asked Apr 26 '11 18:04

Trent Scott


2 Answers

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
like image 150
Will Ayd Avatar answered Oct 05 '22 18:10

Will Ayd


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.

like image 44
ipd Avatar answered Oct 05 '22 20:10

ipd