我正在制作一个仅 API 的 Phoenix 应用程序。我有 Ruby on Rails 背景,所以请耐心等待。
假设我有一个用户模型email
, password
, password_hash
, and role
fields.
我需要限制role
and password_hash
来自用户输入的字段,或将其列入白名单email
and password
字段。现在任何人都可以以管理员身份发布此注册:
{
"user": {
"email": "[email protected]",
"password": "testpw",
"password_hash": "shouldn't allow user input",
"role": "admin"
}
}
这通常在 Rails 中使用强参数来完成,这将删除未明确指定的字段。
如何使用最佳实践对 Phoenix 进行限制/白名单参数?
这是我在 user_controller 中的创建方法:
def create(conn, %{"user" => user_params}) do
changeset = User.registration_changeset(%User{}, user_params)
...
...
end
这是模型 user.ex 中的我的架构和变更集。我正在跟进本教程中,它说“我们通过原始变更集传输新变更集”
schema "users" do
field :email, :string
field :password, :string, virtual: true
field :password_hash, :string
field :role, :string
timestamps()
end
def changeset(model, params \\ :empty) do
model
|> cast(params, ~w(email), [])
|> downcase_email()
|> unique_constraint(:email)
|> validate_format(:email, ~r/@/)
end
def registration_changeset(model, params) do
model
|> changeset(params)
|> cast(params, ~w(password), [])
|> validate_length(:password, min: 6)
|> put_password_hash()
end
凤凰城的scrap_params 关闭,但这听起来不像我需要的。
我认为我可以通过模式匹配来实现这一点,但我不确定如何实现。