Complex Strong Parameters

#16 Complex Strong Parameters
8/28/2015

Summary

Make your strong parameters do more by extracting the logic in order to maximize the ability and security of your application.
1
rails security parameters

Summary

application_controller.rb    def permitted_params
      @permitted_params ||= Params::PermittedParams.new(params, current_user)
    end
    helper_method :permitted_params
app/strong_params/permitted_params.rb    class PermittedParams < Struct.new(:params, :current_user)
      include Params::User
    end
app/strong_params/params/user.rb    module Params
      module User
        def user
          params.require(:user).permit(*user_attributes)
        end

        def user_attributes
          [].tap do |attributes|
            attributes << :first_name
            attributes << :last_name
            attributes << :role if current_user.admin?
            attributes << :email
            attributes << :profile_image
          end
        end
      end
    end
users_controller.rb    @user.update(permitted_params.user)
_form.html.erb     <%= f.input :role, collection: User.roles.keys.map { |k| [k.titleize,k] } if permitted_params.user_attributes.include? :role %>
635114?v=3&s=64
kobaltz said 11 months ago:

They are very similar. However, not every application needs pundit. Sometimes a simple role based authorization is sufficient. While I love using a number of gems, it is sometimes better to roll your own solution as it will be something that you can better maintain. Regardless, this episode is meant to show the extraction of strong parameters and allow them to do something a bit more complex. I'll be covering pundit in depth in a future episode.

Personally, I try not to rely on before_actions for security. In some instances, it makes sense. In your example, I would have something similar in an admin namespace. However, I would still build out the proper authorizations in the admin namespace as it would allow for easier expansion down the road. For example, if I have two roles, admin and user, but later want to add a maintainer with certain access within the admin namespace, the framework is already created for the admin and would need to be expanded for a maintainer role.

Overall, I still prefer the extraction of the strong parameters as I have displayed as it allows for the code to be better compartmentalized. However, when compared to Pundit's strong params approach, it is most likely a matter of preference.

901101?v=3&s=64
mabel said 9 months ago:

Really useful pattern. Tnx!

Login to Comment