varvet / pundit

Minimal authorization through OO design and pure Ruby classes
MIT License
8.28k stars 630 forks source link

`authorize` method brings up a noMethod error for warden Devise #665

Closed oscarlaf03 closed 3 years ago

oscarlaf03 commented 3 years ago

application_controller.rb

class ApplicationController < ActionController::Base
  include Pundit
  #[...]
end

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

stuff_policy.rb


class StuffPolicy < Struct.new(:user, @stuff)
  class Scope < Scope
    def resolve
      scope.all
    end
  end
  def show_stuff?
    return true # for now just testing for now until I can actually get ti working to write the test logic
  end
end

stuff_controller.rb Note that there is no Stuff model just a StuffController thus I am using a "Headless Policy"

class StuffController < ApplicationController
  #[...]
  def  show_stuff(id_to_request_my_stuff_from_another_api_service)
    @stuff = fetch_my_sutff(id_to_request_my_stuff_from_another_api_service) # Returns an Hash with key, values of my  expected Stuff
    authorize @stuff, :show_stuff?  
  end
end

Error message

all the above produces

NoMethodError: undefined method `env' for nil:NilClass
Did you mean?  end
from /home/oscareduardoortizgarcia/.rbenv/versions/2.6.6/lib/ruby/gems/2.6.0/gems/devise-4.5.0/lib/devise/controllers/helpers.rb:143:in `warden'

.rbenv/versions/2.6.6/lib/ruby/gems/2.6.0/gems/devise-4.5.0/lib/devise/controllers/helpers.rb:143

     #[...]
     # The main accessor for the warden proxy instance
      def warden
        request.env['warden'] or raise MissingWarden
      end

Question

What am I doing wrong here?, Why is there a nil for env on the devise gem?

This error goes away when I remove authorize from my stuff_controller.rb file

So I suspects I am not configuring something properly regarding pundit and devise but I don't know what

Thanks a lot for the help

Linuus commented 3 years ago

Are you showing the real code here? Nothing in pundit should conflict with Devise.

oscarlaf03 commented 3 years ago

@Linuus thanks for looking into this I just realized I am hitting my StuffController without first creating an user thus all the devise methods fail