Prevent injection of malicious characters
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
def create(conn, %{"user" => user_params}) do
%User{} |> User.changeset(user_params) |> Repo.insert!()
send_resp(conn, 200, "User created")
end
end
In this Elixir code, the application takes user input directly from the request parameters and uses it to create a new User record. This is insecure because there's no validation on the user_params. An attacker could inject potentially malicious characters or pass in invalid data for certain fields.
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
def create(conn, %{"user" => user_params}) do
changeset = User.changeset(%User{}, user_params)
if changeset.valid? do
Repo.insert!(changeset)
send_resp(conn, 200, "User created")
else
send_resp(conn, 400, "Invalid user data")
end
end
end
In this Elixir code, the application validates user input before using it to create a new User record. The changeset.valid? check ensures that the user_params data is valid before attempting to insert it into the database.