0

I'm using Pundit for my authorization, I'm brand new to it and have only previously worked with Cancan and Cancancan.

I have an index page that does not have a model. This page should ONLY be visible to not logged in users (guests only).

I can only seem to get the page to show for everyone or no-one.

application_policy.rb

class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end

  def index?
    false
  end

  def show?
    false
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope.all
    end
  end
end

splash_controller.rb

class SplashController < ApplicationController

  def index
    authorize :splash, :index?
  end

end

splash_policy.rb

class SplashPolicy < ApplicationPolicy

  # def initialize(user, record)
  #   @user = user
  #   @record = record
  # end

  def index?
    not user?
  end

end

I've commented out a new initialize method, as I assume I need to override this, but I'm not exactly sure on the syntax.

Kobius
  • 674
  • 7
  • 28

1 Answers1

1

I guess pundit is a bit the wrong approch here, since it is built for authorizing users on certain actions and not defining what you see when you are not logged in.

This is usually something I would solve with controller logic, maybe be redirecting all users to some other path, when they are logged in in a before_action.

You might still be able to do it in pundit though by using this method in a headless policy ( https://github.com/varvet/pundit/blob/master/README.md#headless-policies).

 def index?
    user.blank?
 end
smallbutton
  • 3,377
  • 15
  • 27
  • This works great! I've also added the line: "raise Pundit::NotAuthorizedError, "You must be logged in" unless user" to my ApplicationPolicy initialize method to make the app a closed system. Now, you must be logged in to see anything (except the Splash), and only guests can see the Splash. Just curious, would you suggest using Cancancan instead, or is it worth seeing Pundit through? – Kobius Aug 08 '18 at 18:07
  • 1
    Pundit is in my opinion the best authorization framework around. It is simple, flexible and has great maintainers. So go for it ;-) – smallbutton Aug 08 '18 at 19:41