To ensure that sensitive data intended for single use cannot be reused or regenerated.
defmodule VulnerableApp.Accounts do
alias VulnerableApp.Repo
alias VulnerableApp.Accounts.User
def create_user(attrs \ %{}) do
%User{}
|> User.changeset(attrs)
|> Repo.insert()
end
end
The following Elixir code creates a user record with a unique token but does not validate the uniqueness of the token. This means that an attacker could create multiple users with the same token, leading to potential security issues.
defmodule SecureApp.Accounts do
alias SecureApp.Repo
alias SecureApp.Accounts.User
def create_user(attrs \ %{}) do
%User{}
|> User.changeset(attrs)
|> Ecto.Changeset.unique_constraint(:token)
|> Repo.insert()
rescue
Ecto.ConstraintError -> {:error, "Token must be unique"}
end
end
The following Elixir code creates a user record with a unique token and validates the uniqueness of the token. This prevents an attacker from creating multiple users with the same token.