To sanitize and validate input data to prevent HTML injection attacks.
defmodule MyAppWeb.PageController do
use MyAppWeb, :controller
def show(conn, %{"data" => data}) do
render(conn, "show.html", data: data)
end
end
The above code is insecure as it directly uses the user-provided data in the 'data' parameter without any validation or sanitization. This allows an attacker to inject HTML code that will be rendered and potentially execute malicious scripts when viewed in a browser.
defmodule MyAppWeb.PageController do
use MyAppWeb, :controller
def show(conn, %{"data" => data}) do
sanitized_data = Phoenix.HTML.html_escape(data)
render(conn, "show.html", data: sanitized_data)
end
end
The code is now secure as it uses the 'html_escape' function from the Phoenix.HTML module to sanitize the user-provided data before rendering it. This ensures that any HTML code provided by the user is escaped and rendered as plain text, preventing any potential HTML injection attacks.