To prevent unauthorized data access and manipulation through NoSQL Injection attacks
defmodule MyAppWeb.PageController do
use MyAppWeb, :controller
def show(conn, %{"id" => id}) do
page = Mongo.find(:mongo, "pages", %{"_id" => id}) |> Enum.to_list()
json(conn, page)
end
end
In this insecure code, the Elixir/Phoenix application accepts an ID from user input and uses it directly in a MongoDB query. This can be exploited for a NoSQL Injection attack, leading to unauthorized data access or manipulation.
defmodule MyAppWeb.PageController do
use MyAppWeb, :controller
def show(conn, %{"id" => id}) do
id = String.replace(id, "$", "") |> String.replace(".", "")
page = Mongo.find(:mongo, "pages", %{"_id" => id}) |> Enum.to_list()
json(conn, page)
end
end
In this secure code, the application now sanitizes the user input by replacing potential NoSQL Injection attack characters '$' and '.'. The sanitized input is then used in the MongoDB query.