Prevent the creation of more than four beneficiaries per policy
def create(conn, %{"policy" => policy_params, "beneficiaries" => beneficiaries_params}) do
%Policy{}
|> Policy.changeset(policy_params)
|> Ecto.Changeset.cast_assoc(:beneficiaries, with: &Beneficiary.changeset/2)
|> Repo.insert()
send_resp(conn, :ok, "Policy created successfully")
end
This insecure code example shows an Elixir Phoenix application that creates a new policy with associated beneficiaries. However, there's no validation on the server side to restrict the number of beneficiaries created per policy. This allows for unlimited beneficiaries to be associated with a single policy, bypassing the intended restriction.
def create(conn, %{"policy" => policy_params, "beneficiaries" => beneficiaries_params}) do
if Enum.count(beneficiaries_params) > 4 do
send_resp(conn, :bad_request, "Cannot associate more than 4 beneficiaries with a policy")
else
%Policy{}
|> Policy.changeset(policy_params)
|> Ecto.Changeset.cast_assoc(:beneficiaries, with: &Beneficiary.changeset/2)
|> Repo.insert()
send_resp(conn, :ok, "Policy created successfully")
end
end
In this secure code example, a validation function has been added to the controller. This function checks the length of the beneficiaries list before the policy is created. If more than four beneficiaries are associated with a policy, it returns an error response.