Authorization problem with pundit

0

In the controller lodger I put this function authorize , passing user that is logging into the system, within the #destroy method.

What I need is for only the user admin to 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

Within the lodger_policy file that was generated by pundit I put the def destroy method for it to search for exactly at that location and to check if the user is admin or normal_user

def destroy?
    current_user.admin?
end

As defined in the user model with the enum below

enum role: [:normal_user, :admin]

In the index of the view lodger I still check if the user who is logged in is really 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 is really an admin, he does not authorize to use the delete function.

    
asked by anonymous 03.08.2015 / 19:31

1 answer

0

The problem is the way you are trying to authorize the action.

See this example 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 the authorize is the object that will be checked, not the user. The user is populated automatically by pundit, also realize that the user variable that is how the logged in user is passed to pundit should be used.

    
04.08.2015 / 14:43