2013-04-20 99 views
3

我得到以下错误:权限Ruby Gem可以与注销用户一起使用吗?

undefined method `can_read?' for nil:NilClass 

..when试图用登出用户访问产品页面。目前,我有

class ProductAuthorizer < ApplicationAuthorizer 

    def self.readable_by?(user) 
    true 
    end 

end 

我想甚至允许未登录的用户查看页面。这可能吗?

我试图改变默认的用户方法:

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

然而,这会导致问题,我的服务器将不会开始。

回答

8

好吧,我发现这个在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.

嗨,我只是把这个

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 
相关问题