[英]How use customer hash function for user in rails?
In my user model I have在我的用户模型中,我有
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "password_digest"
end
I don't understand how t.string "password_digest"
work in rails?我不明白t.string "password_digest"
在 rails 中是如何工作的? Will it use a default hash function?它会使用默认的哈希函数吗?
Rails will not automatically do anything with your column just because its named password_digest
. Rails 不会仅仅因为您的列名为password_digest
就自动对它做任何事情。 You actually have to implement password encryption for anything to happen.您实际上必须为发生的任何事情实施密码加密。
Rails introduced has_secure_password
in 3.1 to create a standardized way to handle password encryption and avoid the pitfalls of reinventing the password encryption wheel. Rails 在 3.1 中引入了has_secure_password
来创建一种标准化的方式来处理密码加密并避免重新发明密码加密轮的陷阱。
# make sure you add bcrypt to the gemfile and run bundle install
class User < ApplicationRecord
has_secure_password
end
It adds a password=
setter on the model which hashes the password with bcrypt and sets the password_digest
.它在模型上添加了一个password=
setter,用bcrypt散列密码并设置password_digest
。 It also adds a password_confirmation=
setter and validations.它还添加了password_confirmation=
setter 和验证。
You can then authenticate users by calling:然后,您可以通过调用来验证用户:
class SessionsController
def create
# will be nil or false if the email or password does not check out
@user = User.find_by(params[:email])&.authenticate(params[:password])
if @user
session[:user_id] = @user.id
redirect_to '/somewhere'
else
render :new, notice: 'Invalid email or password'
end
end
end
This compares the result of hashing params[:password]
to the values stored in the database.这将散列params[:password]
的结果与存储在数据库中的值进行比较。 Of course you should not really reinvent the authentication wheel if you don't want to learn more about wheels.当然,如果您不想了解有关轮子的更多信息,您不应该真正重新发明身份验证轮子。 For production apps you should really choose battle tested solutions like Devise.对于生产应用程序,您应该真正选择经过实战考验的解决方案,例如 Devise。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.