Authorisation problem with Pundit

Asked

Viewed 78 times

0

On the controller lodger put this function authorize, passing user who is logging into the system, within the method #destroy.

What I need is that only the user admin can perform the deletion operation.

 def destroy
    authorize current_user

    @lodger.destroy
    respond_to do |format|
      format.html { redirect_to lodgers_url, notice: 'Lodger was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

Inside the archive lodger_policy that was generated by Pundit I put the method def destroy to fetch him exactly at that location and make the check if the user is admin or normal_user

def destroy?
    current_user.admin?
end

as defined in the user model with Enum below

enum role: [:normal_user, :admin]

and in the index of the Lodger view I still check if the logged in user is even the admin, as follows:

<% if current_user.admin? %>
<li><%=current_user.admin?%></li>   ##isto é, aqui nessa linha ele retorna true se o usuário realmente for admin
<%= render 'admin_index' %>
<% else %>
<%= render 'normal_user_index' %>
<% end%>

but the problem is that even if it returns true at the beginning of the index, confirming that the user really is an admin it nay authorizes using the deletion function.

1 answer

0

The problem is the way you’re trying to authorize the action.

See this example of authorization class:

class PostPolicy
  attr_reader :user, :post

  def initialize(user, post)
    @user = user
    @post = post
  end

  def delete?
    user.admin?
  end
end

To authorize delete, it should be called in the controller:

def delete
  @post = Post.find(params[:id])
  authorize @post
  ...
end

Note that: What should be passed to authorize it is the object that will be checked and not the user. The user is filled automating by Pundit, also note that should be used the user variable which is how the logged-in user is passed to Pundit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.