Ensure only the authentic user can change the account password
defmodule VulnerableController do
use MyApp.Web, :controller
def change_password(conn, %{"new_password" => new_password}) do
user = get_current_user(conn)
User.change_password(user, new_password)
send_resp(conn, 200, "Password changed")
end
end
The following Elixir code is vulnerable because it allows users to change their passwords without verifying their current password. An attacker who has access to a user's session could change the password without the user's knowledge.
defmodule SecureController do
use MyApp.Web, :controller
def change_password(conn, %{"current_password" => current_password, "new_password" => new_password}) do
user = get_current_user(conn)
if User.check_password(user, current_password) do
User.change_password(user, new_password)
send_resp(conn, 200, "Password changed")
else
send_resp(conn, 400, "Incorrect current password")
end
end
end
The following Elixir code is secure because it requires the current password to change the password. This helps ensure that the request is made by the legitimate user.