1

I am building a website where a user can see multiple poetries or write his own. I am using Devise and Pundit for authentication and authorization.

When the user goes to the main link (http://0.0.0.0:3000/), I want him to be able to see the page even if he is NOT logged in. The HOME page is simply an HTML page with a buttons that, if clicked, redirects to all the poetries (poetries controller).

However, I am experiencing the following error:

Pundit::AuthorizationNotPerformedError in PagesController#home

application_controller.rb

class ApplicationController < ActionController::Base
  include Pundit

  protect_from_forgery with: :exception
  before_action :authenticate_user!

  after_action :verify_authorized, :except => :index, unless: :devise_controller?
  after_action :verify_policy_scoped, :only => :index, unless: :devise_controller?

  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  private

  def user_not_authorized
    flash[:alert] = "Non sei autorizzato a eseguire questa azione"
    redirect_to(root_path)
  end

end

pages_controllers.rb

class PagesController < ApplicationController
  include Pundit

  skip_before_action :authenticate_user!, only: [:home]
  # skip_after_action :verify_authorized, except: [:home]
  # after_action :verify_authorized, except: [:home]
  # before_action :authenticate_user!, except: [:home,]


  def home
  end
end

I tried following this guide: Pundit::AuthorizationNotPerformedError But I keep getting the same error.

I did NOT create a pages_policy.rb but I do not think this is the problem.

Magofoco
  • 5,098
  • 6
  • 35
  • 77

1 Answers1

2

Solved it. Since PagesController is inheriting from ApplicationController, and the latter contains before_action :authenticate_user!, I have to write the following in PagesController:

class PagesController < ApplicationController
  include Pundit
    skip_after_action :verify_authorized, only: [:home]

    skip_before_action :authenticate_user!, only: [:home]

  def home
  end
end
Magofoco
  • 5,098
  • 6
  • 35
  • 77