0

I have a User model with a boolean switch to designate admin t/f. My current application controller:

class ApplicationController < ActionController::Base
  protect_from_forgery

  def after_sign_in_path_for(user)
    if current_user.admin?
        admin_index_path
    else
        dashboard_index_path
    end
  end
end

My current admin controller:

class AdminController < ApplicationController

    def index
        if current_user.admin?

            admin_index_path
        else

            home_index_path
        end
    end
end

The goal is of course to only allow access to the admin index page to admin users. The redirect works fine when I sign in as admin, but I'm getting a NoMethodError in AdminController#index error when I navigate to admin_index_path as an non-admin user (undefined method `admin?' for nil:NilClass). Help on this issue? I feel like there is probably a CanCan solution that would be more elegant and secure, but I haven't found a good explanation of how to accomplish that. Thoughts? Thanks in advance!

settheline
  • 3,333
  • 8
  • 33
  • 65
  • You get this message because you have no current_user. It just points to nil. That's seem strange for me because it has to point on user if you use devise. Are you overriding current_user somewhere? – Ivan Shamatov Jul 02 '13 at 04:31
  • Ah I think I see. I was actually trying to navigate to the admin path while not signed in as any user at all. That's probably why it threw that error. Not sure how to handle users who aren't signed in, as I won't be requiring a sign in to use the applicaiton. Thoughts? – settheline Jul 02 '13 at 05:43

2 Answers2

0

Use before_filter

https://github.com/plataformatec/devise#controller-filters-and-helpers

class AdminController < ApplicationController

 before_filter :authenticate_user!, only: [:index]
 before_filter :is_admin, only: [:index]

 def index
 end

 private

  def is_admin
  if user_signed_in?
   if current_user.admin?
     true
   else
     redirect_to home_index_path
   end
  else
    redirect_to login_path
  end
 end

end

user_signed_in? check user have sign in and current_user.admin? check is admin when access index

or

def is_admin
 if current_user.nil?
  redirect_to login_path
 else
   if current_user.admin?
     true
   else
     redirect_to home_index_path
   end
 end
end
rails_id
  • 8,120
  • 4
  • 46
  • 84
0

use resource instead of use it is more generic

def after_sign_in_path_for(resource) if current_user.admin? admin_index_path else dashboard_index_path end end and

and Just put before_filter :authenticate_user! in index action. it will resolve your proble. you got nil class error because current_user variable is not set as user not signed in.

Amitkumar Jha
  • 1,313
  • 1
  • 10
  • 15