I am using the following query to find nearest locations google maps. Is it immune to the Sql injection. If not can anyone help me to get rid of it.
AlphaCourses.find_by_sql("SELECT *,( 6371 * acos( cos( radians( #{@latitude} ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians( #{@longitude} ) ) + sin( radians( #{@latitude} ) ) * sin( radians( latitude ) ) ) ) AS distance FROM alpha_courses HAVING distance <= #{@radius} ORDER BY distance LIMIT 200")
Thanks in advance.
Summary. As you can see, Ruby on Rails, by default, won't save you from all SQL injection attack attempts. Some of the methods of its built-in library, Active Records, prevent these types of attacks automatically, but others don't. However, it's not that difficult to make your application secure.
The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.
To avoid SQL injection, all input that are to be concatenated in dynamic SQL must be correctly filtered and sanitized.
From: http://guides.rubyonrails.org/active_record_querying.html#pure-string-conditions
This code
....("orders_count = ?", params[:orders])
is highly preferable to this code:
....("orders_count = #{params[:orders]}")
because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database as-is. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.
Apply this to your example!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With