gpt4 book ai didi

ruby-on-rails - Has_secure_password Bcrypt 给出零密码

转载 作者:太空宇宙 更新时间:2023-11-03 16:41:39 24 4
gpt4 key购买 nike

我正在尝试跟随 Michael Hartl 的 Ruby on Rail 一书,我在第 10 章,试图允许用户编辑他们的配置文件设置,这是最奇怪的错误 - bcrypt 的 password_digest 正在破坏我的测试。

用户.yml

user:
name: Example User
email: example@gmail.com
password_digest: <%= User.digest("password") %>

当我在 Rails 控制台中运行它时,这就是我所看到的

user.valid? => false

user.errors.full_messages=> ["密码不能为空", "密码太短(最少6个字符)"]

用户.rb

class User < ApplicationRecord
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
before_save {
self.email.downcase!
}

validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
has_secure_password

# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
end

我正在使用 bcrypt 版本“3.1.11”

我的测试代码

 def setup
@user = users(:marko)
end

test "successful edit" do
log_in_as(@user)
get edit_user_path(@user)
name = "Foo bar"
email = "foo@bar.com"
patch user_path(@user), params: { user: {
name: name,
email: email,
password: "password",
password_confirmation: "password" } }
assert_not flash.empty?
assert_redirected_to @user
follow_redirect!
@user.reload
assert_equal name, @user.name
assert_equal email, @user.email
end

任何想法可能是错误的?

最佳答案

尝试使用下面的代码

user:
name: Example User
email: example@gmail.com
password: "password"

Bcrypt 有一个验证,即创建新记录时 password attr_accessor 应该存在(更新时可选).

您还应该将 allow_blank: true 添加到密码的长度验证 中,因为当密码本身为空/nil 时不需要长度验证

关于ruby-on-rails - Has_secure_password Bcrypt 给出零密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48001180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com