Devise/cancan redirect admin issue

2019-06-09 17:16发布

问题:

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!

回答1:

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


回答2:

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.