Elixir/Phoenix 限制参数,如 Rails 强参数

2023-12-14

我正在制作一个仅 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 关闭,但这听起来不像我需要的。

我认为我可以通过模式匹配来实现这一点,但我不确定如何实现。


实际上,代码的行为符合预期,并且不保存角色字段。 (我正在控制台中读取请求,而不是实际检查数据库。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Elixir/Phoenix 限制参数,如 Rails 强参数 的相关文章

随机推荐