Elixir/Phoenix限制了Rails强参数之类的参数 [英] Elixir/Phoenix restrict params like Rails strong params
问题描述
我正在制作仅API的Phoenix应用程序.我来自Ruby on Rails背景,所以请多多包涵.
I am making an API only Phoenix app. I come from a Ruby on Rails background, so bear with me.
说我有一个带有email
,password
,password_hash
和role
字段的用户模型.
Say I have a User model with email
, password
, password_hash
, and role
fields.
我需要限制用户输入的role
和password_hash
字段,或者将email
和password
字段列入白名单.现在,任何人都可以以管理员身份发布此注册信息:
I need to restrict the role
and password_hash
fields from user input, or whitelist the email
and password
fields. Right now anyone could POST this sign up as an admin:
{
"user": {
"email": "test3@test.com",
"password": "testpw",
"password_hash": "shouldn't allow user input",
"role": "admin"
}
}
这通常是在Rails中使用强大的参数完成的,这会去除未明确指定的字段.
This is typically accomplished in Rails using strong params, which will strip out fields that are not explicitly specified.
如何使用最佳做法将Phoenix的参数限制/列入白名单?
这是我在user_controller中的创建方法:
This is my create method in my user_controller:
def create(conn, %{"user" => user_params}) do
changeset = User.registration_changeset(%User{}, user_params)
...
...
end
这是模型user.ex中的架构和变更集.我正在追踪在本教程中,它说我们将新的变更集通过我们原来的变更集进行传递"
And here is my schema and changesets in the model, user.ex. I'm following this tutorial, it says "we pipe the new changeset through our original one"
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
Phoenix的 scrub_params已关闭,但是没有.听起来不像我需要的东西.
Phoenix's scrub_params is close, but it doesn't sound like what I need.
我认为我可以通过模式匹配来完成此操作,但是我不确定如何实现.
I think I can accomplish this by pattern matching but I'm not sure how.
推荐答案
实际上,代码的行为符合预期,并且不保存角色字段. (我正在控制台中读取请求,而不是实际检查数据库.)
Actually the code behaves as expected and does not save the role field. (I was reading the request in the console instead of actually checking the database.)
这篇关于Elixir/Phoenix限制了Rails强参数之类的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!