To prevent users from manipulating hidden fields in the application that could lead to undesired behaviors
def update(conn, %{"user" => user_params}) do
user = Repo.get!(User, user_params["id"])
case Accounts.update_user(user, user_params) do
{:ok, user} -> redirect(conn, to: user_path(conn, :show, user))
{:error, _changeset} -> :error
end
end
This code snippet is vulnerable because it accepts all the parameters from the client-side, including the id field. An attacker could manipulate this id field in a hidden form input, thus potentially altering data they do not have access to.
def update(conn, %{"user" => user_params}) do
user = Accounts.get_user!(conn.assigns.current_user.id)
case Accounts.update_user(user, user_params) do
{:ok, user} -> redirect(conn, to: user_path(conn, :show, user))
{:error, _changeset} -> :error
end
end
In this secure version, instead of getting the user's id from the client-side, it's obtained from the server-side using the authenticated user's session. This prevents attackers from manipulating the id field.