ankane/pretender

not working with devise scope

RORrvtech opened this issue ยท 4 comments

steps

  1. impersonate_user(normal_user)

  2. put debugger in routes.rb
    authenticate :user, lambda { |u| debugger; u.admin? } do
    mount Sidekiq::Web => '/sidekiq'
    root to: "users#index", as: :admin_root
    end

     authenticate :user, lambda { |u| u.normal_user? } do
       root 'activities#index', as: :authenticated_root
     end
    

Result => u is admin user. all root url are wrong hence. cancancan raises multiple redirect. because of below in applicaiton controller

rescue_from CanCan::AccessDenied do |exception|
    redirect_to(main_app.root_url, :alert => exception.message)
end

Hey @RORrvtech, Pretender only works at the controller level unfortunately.

Yes, I realised that, Placing workaround here if anyone facing same issue.

in ApplicationController

rescue_from CanCan::AccessDenied do |exception|
    path = get_root_path
    redirect_to(path, :alert => exception.message)
  end
  def get_root_path
      if current_user&.normal_user?
        activities_path
       elsif current_user&.dummy_user?
        activities_path
       elsif current_user&.admin?
        users_path
       else
        home_path
      end
  end
 helper_method :get_root_path

In in UsersController

  def impersonate
       authorize! :impersonate, User
       user = User.find(params[:id])
       impersonate_user(user)
       redirect_to get_root_path
   end

   def stop_impersonating
       stop_impersonating_user
       redirect_to get_root_path
   end
  1. anyone looking why "&" is there can google for it.
  2. You will not face any redirects due to different roles.

Thanks for sharing ๐Ÿ‘

Solution for sidekiq , etc.:

  constraints(lambda { |req| User.find(req.session[:impersonated_employee_id]).admin? }) do
    mount Sidekiq::Web => '/sidekiq'
  end

Would be nice to have it in the docs