user938438932
user938438932

Reputation: 55

Rails possible SQL injection error

I am trying to write a method based on sql query and this is what i wrote so far

class Hospital
  class Doctors < ActiveRecord::Base

  self.table_name = 'vDoctorDetails'

def self.doctor_status(user_id)

      doctor_department = ActiveRecord::Base.connection.quote('Abc')
      doctor_status = ActiveRecord::Base.connection.quote('Y')

  Doctors
     .select('vDoctorDetails.DoctorInfo')
     .where("vDoctorDetails.doctor_id = #{user_id}"}
     .where("vDoctorDetails.doctor_department = #{doctor_department}"}
     .where("vDoctorDetails.doctor_status = #{doctor_status}"}
     .first
    end
   end
  end

I am going by fat model and skinny controller concept so creating this method in model. When i test this in console it works fine but when i tried to deploy it to github master branch, brakeman pro throws error

sql injection found near          .select('vDoctorDetails.DoctorInfo')
         .where("vDoctorDetails.doctor_id = #{user_id}"}

I tried creating scopes but then i will have to call all scopes in controller. what'd be the best way to write this method so i can get rid of the sql injection error?

Upvotes: 1

Views: 153

Answers (2)

spickermann
spickermann

Reputation: 106882

You can rewrite the whole query like this

def self.doctor_status(user_id)
  where(doctor_id: user_id, doctor_department: 'Abc', doctor_status: 'Y')
    .select('DoctorInfo')
    .first
end

and Rails would take care of correctly quoting the values and adding the table name.

Read about query syntax and hash conditions in the Rails Guides.

Upvotes: 0

Susan Joshi
Susan Joshi

Reputation: 134

Try:

Doctors
 .select('vDoctorDetails.DoctorInfo')
 .where('vDoctorDetails.doctor_id = ?', user_id)
 .where('vDoctorDetails.doctor_department = ?', doctor_department)
 .where('vDoctorDetails.doctor_status = ?', doctor_status)
 .first

Upvotes: 2

Related Questions