Prevent unauthorized extraction or manipulation of data in the database
def get_user_data(conn, %{"id" => id}) do
Repo.query("SELECT * FROM users WHERE id = " <> id)
end
The code above is vulnerable to SQL Injection because it directly concatenates a user-provided string (id) into a SQL query. An attacker could provide a malicious string that alters the SQL query to expose sensitive data or execute unauthorized SQL commands.
def get_user_data(conn, %{"id" => id}) do
id = String.to_integer(id)
query = from u in "users", where: u.id == ^id
Repo.one(query)
end
The code above is secure because it uses Ecto's query API to construct the SQL query, which automatically escapes variables to prevent SQL Injection. It also converts the user input to an integer, providing an extra layer of security.