0

I am trying to use Pundit to authenticate access to some static views that require no database interaction:

class StaticController < ApplicationController
    include Pundit
    authorize :splash, :home?

    def home end
end

Below is my static policy. The home? policy always returns true, so I should be able to access the home view.

class StaticPolicy < Struct.new(:user, :static)
    def initialize(user, resource)
        @user = user
        @resource = resource
    end

    def home?
        true
    end
end

Instead I get this:

undefined method `authorize' for StaticController:Class

Pundit works perfectly if I'm authorizing a model:

def forums_index
    @forums = Forum.all
    authorize @forums
end

However, if I try to use the authorize method outside of an action that doesn't make use of a model I get:

undefined method `authorize' for StaticController:Class
Starkers
  • 10,273
  • 21
  • 95
  • 158

1 Answers1

0

Well, AFAIK you'll always have to authorize against either an object or a class, while CanCan already "load_and_authorize_resource", when using Pundit you already know that you have to load and authorize something yourself (sorry if I'm being too obvious here).

That said and considering that your view doesn't have DB interation, it seems to me that the best solution for your case is make some custom authorization against your user, something like

class StaticPolicy < Struct.new(:user, :static)
  def initialize(user, resource)
    @user = user
    @resource = resource
  end

  def home?
    authorize @user, :admin # or suppress the second parameter and let the Policy use the 'home?' method
    true
  end
end

and in your UserPolicy something like

class UserPolicy < ApplicationPolicy
  def admin # or def home?, it's up to you
    user.admin?
  end
end

I didn't test it, but that's the main idea, does it make any sense? Is it clear?

Please give it a try and post any impressions, hope it helps :)

Miguelgraz
  • 4,376
  • 1
  • 21
  • 16