简体   繁体   中英

Rails - Pundit, how to show controller index only for not logged in users

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM