Question

I get the following error:

  undefined method `can_read?' for nil:NilClass

..when trying to access a product page with a logged-out user. At the moment I have

class ProductAuthorizer < ApplicationAuthorizer

  def self.readable_by?(user)
    true
  end

end

I'd like to allow even non-logged in users to see the page. Is this possible?

I tried changing the default user method to:

config.user_method = :current_user ||= User.new

However, this causes problems, and my server won't even start.

Was it helpful?

Solution

Ok I found this at https://github.com/nathanl/authority/pull/32:

OK! For the sake of anyone else reading this issue, Chris and I chatted and agreed about the best way to proceed. Here's the gist of it.

Authority won't specially handle nil users or give a specific option to do so. We want to limit Authority to authorization and keep authentication totally separate. If there's no user signed in, that's an authentication concern; Authority can't meaningfully answer the question "can this user do X?" if it isn't given a user or something that quacks like one.

Besides the philosophical point, having authentication handle this is a better user experience. If an admin has forgotten to sign in and attempts some admin-only action, it would be confusing to them to say "access denied". It would be much more helpful to say "please sign in".

What developers using Authority can do is:

Have something like Devise's before_filter :authenticate_user! running prior to any Authority checks on the request (since any action that requires authorization clearly requires authentication). Have their user method return a NullUser object that quacks like a user, then have their authorizers know what to do with those What Authority can do is improve the error it gives you if you pass nil or anything else that doesn't quack like a user. Chris is going to implement this.

Hi I've just put this

  class ApplicationController < ActionController::Base
      def current_or_null_user
        if current_user == nil
          User.new
        else
          current_user
        end
     end
  end

...

Authority.configure do |config|
   config.user_method = :current_or_null_user
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top