When we first start learning Ruby on Rails, one of the things we quickly pick up is that Active Record helps protect our applications from SQL injection attacks. However, even with this powerful ORM, our apps can still become vulnerable if we’re not careful with how we write our code.
BAD PRACTICE
class UsersController < ApplicationController
def index
@users = User.where("users.name = #{params[:name]}")
end
end
What would happen if a malicious user passed in the following URL parameter:
name=John;DROP TABLE USERS;
The code would execute exactly what the attacker has input, causing the entire USERS table to be dropped from your database—leaving you with potentially devastating data loss.
GOOD PRACTICE
class UsersController < ApplicationController
def index
@users = User.where(name: params[:name])
end
end
In this example, Rails automatically escapes the input, ensuring that any user-provided data is safely handled, preventing harmful SQL code from being executed
This is a simple example, but it shows how easy it is to make a mistake when using direct SQL queries in your Rails app. If you ever need to use raw SQL, always make sure to properly sanitize any user input to avoid security risks like SQL injection.
Trebate inženjere koji ovako pišu kod?
Povezujemo provjerene programere, dizajnere, QA i voditelje projekata s tvrtkama i startupima diljem EU. Recite nam što trebate i predložit ćemo kandidate koji odgovaraju.
Dogovorite 30-minutni pozivJoš s bloga
-
05. studenoga 2024.
Why Metaprogramming is Cool
Every Ruby on Rails developer has likely used Rails.env.production? , Rails.env.development? , or similar c...
-
22. listopada 2024.
Thread-Safety in Ruby on Rails: Basic Example With Race Conditions
The Global Interpreter Lock GIL in Ruby prevents true multi core CPU usage in a Rails app, but there is sti...
-
14. kolovoza 2023.
How to add a domain name hosted on Heroku to name.com provider
If you are searching for a domain provider for your website hosted on Heroku, make sure to check whether th...