0

I am using Pundit to deal with authorizations. I want my user's profiles to be visible by everyone so in my user_policy.rb, I have:

 def show?
    true  # Anyone can view a show
  end

In my users/show.html.erb, the "edit profile" button is displayed only if:

<% if policy(@user).update? %>
  <!--  show edit button  -->
<% end %>

The issue is that when I try to access a profile and I'm not logged in, Pundit is looking for a "user":

def update?
  record == user || user.admin == true # Only user creator can update it
end

I have an error saying that user is nil so admin is undefined. I wanted to do this:

def update?
  if user_signed_in?
    record == user || user.admin == true # Only user creator can update it
  else
    false
  end
end

but user_signed_in? is a devise helper, not accessible in Pundit. Is there an equivalent I could use or a better way to do this ?

Graham Slick
  • 6,692
  • 9
  • 51
  • 87

2 Answers2

3

As Richard said, you should verify that there is a user first, and if he is the owner or an admin. I like to read it this way:

  def update?
    user.present? && (is_owner? || is_admin?)
  end

private

 def is_owner?
   record.user == user
 end
 def is_admin?
   user.admin #In your case user.admin is simple enough so you don't need that, but sometimes it's not.
 end
Yimanei
  • 242
  • 2
  • 8
  • user.present will also handle the case of a registered but unconfirmed user - a devise functionality. Quite convenient – Jerome Jul 03 '16 at 09:39
2

Couldn't you just check that user variable exists first?

def update?
  user && (record == user || user.admin == true) # Only user creator can update it
end
RichardAE
  • 2,945
  • 1
  • 17
  • 20