Search code examples
ruby-on-railsdevisepundit

Rails Pundit how the policies are worknig?


I have a web application in ruby on rails with devise as the authentication and pundit as the authorization.

I have a model user with an integer role attribute with values 0, 1, 2, for visitor, vip, and admin respectively. I also have a scaffold, say Page that I want just vip and admin to have access to and not visitor users.

In page_policy.rb I have

def index?
  current_user.vip? or current_user.admin?
end

and in pages_controller.rb I have a line authorize current_user. Although I have given access to vip but it is available just for admin user. Where have I been wrong with the code?

Thank you


Solution

  • I assume you have properly set up your predicate methods vip? and admin? on the User model, and these work as expected? Can you check the result of calling each of these methods on your current user?

    Pundit actually passes the result of current_user to your policy initializer, and you can access that via the user method inside your policy methods. Also I would be careful of using the or operator in this context (see http://www.virtuouscode.com/2010/08/02/using-and-and-or-in-ruby/).

    So I would try:

    def index?
      user.vip? || user.admin?
    end
    

    Also, pundit expects you to pass the resource you are checking to the authorize method, not the user object. If you don't have an instance to pass, you can pass the class:

    authorize Page