Prevent unauthorized privilege escalation
def update_user(conn, %{"user" => user_params}) do
user = Repo.get(User, user_params["id"])
changeset = User.changeset(user, user_params)
Repo.update!(changeset)
# further code
end
This code is vulnerable because it directly updates user information, including their privileges, based on the provided parameters without any checks. An attacker could exploit this to grant themselves excessive permissions.
def update_user(conn, %{"user" => user_params}) do
user = Repo.get(User, user_params["id"])
if conn.assigns.current_user.id == user.id and !user_params["role"] do
changeset = User.changeset(user, user_params)
Repo.update!(changeset)
else
# return error
end
# further code
end
The secure code example checks whether the current user is the same as the one being updated, and also checks that the 'role' parameter is not being changed. This helps to prevent privilege escalation attacks by not allowing users to modify their own privileges.