Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically remove Active Admin form inputs with Pundit permitted attributes?

I have a Rails 4 app using Active Admin 1.0.0.pre1 in conjunction with pundit 0.3.0 for authorization which has worked flawlessly thus far, but I'm having trouble figuring out a good way automatically customize forms based on a user's role.

Given these models:

ActiveAdmin.register AdminUser do
  permit_params do
    Pundit.policy(current_admin_user, resource).permitted_attributes
  end

  form do |f|
    f.inputs "Admin Details" do
      f.input :role, as: :select, collection: [:manager, :admin]
      f.input :email, as: :email
      f.input :password
      f.input :password_confirmation
    end
    f.actions
  end
end

class AdminUserPolicy < ApplicationPolicy
  def permitted_attributes
    attributes = [:email, :password, :password_confirmation]
    attributes += [:role] if user.has_role? :super_admin
    attributes
  end
end

I'd like for the role input to be automatically removed from the form.

One option would be something along the lines of:

  permitted_attributes = Pundit.policy(current_admin_user, resource).permitted_attributes

  form do |f|
    f.inputs "Admin Details" do
      f.input :role if permitted_attributes.include? :role
      f.input :email
      f.input :password
      f.input :password_confirmation
    end
    f.actions
  end

but, that approach requires the developer to remember which attributes should be checked, seems prone to forgetfulness and isn't exactly DRY. Perhaps, I am going about this the wrong way? All suggestions welcome.

like image 992
Ben Carney Avatar asked Nov 10 '22 16:11

Ben Carney


1 Answers

Intercepting ActiveAdminForm by prepending a module that overrides input with a check against the Pundit policy seems to work well. Here is the implementation I went with:

# /lib/active_admin/permitted_active_admin_form.rb
module PermittedActiveAdminForm
  def permitted_attributes
    policy = Pundit.policy(current_admin_user, resource)
    policy.respond_to?(:permitted_attributes) ? policy.permitted_attributes : []
  end

  def input(*args)
    super(*args) if permitted_attributes.include? args[0]
  end
end


# /config/initializers/active_admin.rb
module ActiveAdmin
  module Views
    class ActiveAdminForm < FormtasticProxy
      prepend PermittedActiveAdminForm
    end
  end
end

# /app/admin/admin_user.rb
ActiveAdmin.register AdminUser do
  permit_params do
    resource ||= AdminUser
    Pundit.policy(current_admin_user, resource).permitted_attributes
  end

  form do |f|
    f.inputs "Admin Details" do
      f.input :role, as: :select, collection: [:manager, :admin]
      f.input :email, as: :email
      f.input :password
      f.input :password_confirmation
    end
    f.actions
  end
end

Thanks to Andrey Deineko for starting me down the right path.

like image 55
Ben Carney Avatar answered Jan 04 '23 01:01

Ben Carney