Search code examples
ruby-on-railsapitypesparametersapplicationcontroller

Convert function params to Hash object in Ruby on Rails


I have to make a change to an API developed in Ruby On Rails that looks like this:

class V0::PythonsController < ApplicationController
  skip_before_action :authorize_request

  # POST v0/python/import
  def import
    result = { status: :error }
    data = eval(AwsTool.decrypt(params["code"])).first
    if data.class == Hash
      user = User.find_by(id: data[:ot_user_id])
      activity_type = ActivityType.find_by(id: data[:activity_type])
      if user.nil?
        result[:msg] = "user not found"
      elsif activity_type.nil?
        result[:msg] = "activity type not found"
      else...

I pass to it some data in the "code" param, that is then decrypted and then explored. I want to add an if clause so when I call the API from a different origin no encryption and decryption takes place. So I have made this change:

class V0::PythonsController < ApplicationController
  skip_before_action :authorize_request

  # POST v0/python/import
  def import
    result = { status: :error }
  if params["origin"] != 'trusted'
    data = eval(AwsTool.decrypt(params["code"])).first
  else
    data = params["code"]
  end
  if data.class == Hash
    user = User.find_by(id: data[:ot_user_id])
    activity_type = ActivityType.find_by(id: data[:activity_type])
    ...

The problem is that data.class is not a Hash object, its a String. I have tried different solutions to convert the object from String to Hash like t_hash and other similar functions but they didn't work. I got some errors about params not being permitted, I tried to add the permit to them but still fails.

Any other idea?


Solution

  • It is failing because you forgot to call eval on the code. Do this:

    data = eval(params["code"])
    

    By the way, evaling input is very dangerous. I hope you trust whoever is using this API.