Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorizing an array of ID's with the Pundit gem

I have a multiple select box for a has_many association. The params come in as:

foo_ids: ["1", "2", "3"]

Using strong parameters, I do not permit this attribute because I would like to authorize it myself so people cannot just put whatever they want in it.

def update
  bar.foos = authorized_foos
  bar.update(baz_params)
  respond_with bar
end

private

  def authorized_foos
    foos = Foo.find(params[:baz][:foo_ids])
    foos.each do |foo|
      authorize foo, :manage?
    end
  end

This approach is going to force me to find all of the foos, loop through them, and authorize each one individually. Is there an easier way to manage has_many authorization, preferably with the Pundit gem?

like image 672
Logan Serman Avatar asked Aug 20 '13 15:08

Logan Serman


People also ask

What is pundit gem?

Pundit is a Ruby gem that handles authorization via a very simple API. Remember that authorization is different from authentication — authentication is verifying that you are who you say you are, and authorization is verifying that you have permission to perform an action.

What is pundit for Ruby?

Pundit provides a set of helpers which guide you in leveraging regular Ruby classes and object oriented design patterns to build a simple, robust and scalable authorization system. Links: API documentation for the most recent version.

What does authorize do in Rails?

Authentication is the process of verifying who you are. Authorization is the process of verifying that you have access to resources.

What is scope pundit?

Pundit creates an instance of class Scope (nested inside the class TaskPolicy) passing along the current_user and the Task model (our scope in this case) as parameters which get set in the @user and @scope instance variables respectively inside the initialize method.


1 Answers

The simplest way to do this is looping. Iterate through each user from the users' array and authorize each and every user. For example,

users_id_array = [1,2,3,4,5,6]

private

  def authorized_users
  users = User.find(params[:group][:user_ids])
  users.each { |u| authorize u, :manage? }
  ...
end

So this is the very basic and simplest answer.

like image 74
Nishant Upadhyay Avatar answered Oct 20 '22 15:10

Nishant Upadhyay