1

I'm using the pundit gem and trying to figure out how to use it to prevent access to an index page that belongs to a user other than the current_user.

The examples only talk about how to scope the results to the current_user but no how to actually prevent access to the page itself if the current_user is NOT the owner of the record.

Any help appreciated

Thanks

Robbo
  • 1,292
  • 2
  • 18
  • 41
  • I would think an index page doesn't belong to any user. Is the goal to restrict access to admins only? – moveson Nov 10 '16 at 20:11
  • @moveson It is the index page for a specific user, it's there page. Perhaps it shouldn't be an index page but a separate action in the users controller like user_posts – Robbo Nov 10 '16 at 21:18
  • That would make more sense to me. The pattern described below should work; just replace `index?` with `user_posts?`. See comment from @Fede Bonisconti below for an alternative suggestion as to where to put the `authorized_to_edit?` logic. If you include it anywhere other than the User model, you will need to call `authorized_to_edit?(current_user)` instead of `current_user.authorized_to_edit?` – moveson Nov 10 '16 at 21:25

1 Answers1

1

Maybe you want something like this? (For class ModelName)

# /policies/model_name_policy.rb

class ModelNamePolicy
  attr_reader :current_user, :resource

  def initialize(current_user, resource)
    @current_user = current_user
    @resource = resource
  end

  def index?
    current_user.authorized_to_edit?(resource)
  end

end

# /models/user.rb

class User < ActiveRecord::Base

  def authorized_to_edit?(resource)
    admin? | (id == resource.created_by) # Or whatever method you want to call on your model to determine ownership
  end

end

EDIT: Note that you will also need to call authorize from your controller to invoke the policy.

moveson
  • 5,103
  • 1
  • 15
  • 32
  • IMO: The idea behind Pundit is to not include your authorization logic within your model. – Fede Bonisconti Nov 10 '16 at 20:54
  • Open to other suggestions. If `authorized_to_edit?` is used in policies for many models, where would you put it? – moveson Nov 10 '16 at 21:02
  • `authorize_to_edit` should be defined in each policy for each model. If some of your models share the same authorization logic, you could use a class/mixin to avoid duplicated code – Fede Bonisconti Nov 10 '16 at 21:15
  • It is the index page for a specific user, it's there page. Perhaps it shouldn't be an index page but a separate action in the users controller like user_posts – Robbo Nov 10 '16 at 21:17