Secure password management
def update_password(conn, %{"id" => id, "password" => password}) do
user = Accounts.get_user!(id)
user
|> User.changeset(%{password: password})
|> Repo.update!()
conn
|> put_flash(:info, "Password updated successfully.")
|> redirect(to: "/")
end
This example represents a password update function in a web application written in Elixir using the Phoenix framework. The function does not verify whether the current user has the right to change the password for the user id provided in the params. An attacker can use this function to change the password of any user, knowing only their user id.
def update_password(conn, %{"id" => id, "password" => password}) do
current_user = get_session(conn, :current_user)
if current_user.id == id do
user = Accounts.get_user!(id)
user
|> User.changeset(%{password: password})
|> Repo.update!()
conn
|> put_flash(:info, "Password updated successfully.")
|> redirect(to: "/")
else
conn
|> put_flash(:error, "You do not have permission to change this user's password.")
|> redirect(to: "/")
end
end
This is the secure version of the previous code. It includes a check to verify that the current user (taken from the session) is the same user for whom the password is being changed.