chaps-io / access-granted

Multi-role and whitelist based authorization gem for Rails (and not only Rails!)
MIT License
774 stars 41 forks source link

errors with non-logged in users #32

Closed vince closed 8 years ago

vince commented 8 years ago

I've got a configure block defined in a pretty standard way:

    role :admin, proc { |user| user.is_admin } do
       can :manage, Post
    end

When I view the page as a non logged in user though I get an error:

undefined method `is_admin' for nil:NilClass

I must be missing something pretty simple -- unless it depends on authentication before authorization? Little help please?

pokonski commented 8 years ago

This is of course expected since current_user is not present. This is something you have to take care of outside Access Granted.

A popular pattern for solving this is always returning some user. For example, we can mock a GuestUser account responding to basic methods and identifying itself as a guest:

class GuestUser
  def is_admin?
    false
  end

  def is_guest?
    true
  end
end

and in your application controller:

def current_user
  super || GuestUser.new
end

this will make sure there's always an instance of a User you can run checks on.

vince commented 8 years ago

Perfect, thanks for the clarification and quick response!

pokonski commented 8 years ago

Glad I could help :+1:

On 14 July 2016 at 16:34, Vince Wadhwani notifications@github.com wrote:

Perfect, thanks for the clarification and quick response!

— You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHub https://github.com/chaps-io/access-granted/issues/32#issuecomment-232683317, or mute the thread https://github.com/notifications/unsubscribe/AAIQ6rqEM2Br-O6RqhgtZ6WbtFuvnc-Rks5qVkjcgaJpZM4JL-0A .

Piotr Okoński piotrek@okonski.org | +48 792 097 151