在Rails 4中禁用has_secure_password password_confirmation检查

Ala*_*ith 7 passwords validation ruby-on-rails

我正在创建一个基本的Ruby on Rails 4项目,允许用户创建帐户,登录等...我正在使用内置has_secure_password来管理密码.我不希望用户必须输入两次密码(即需要password_confirmation输入表单字段和相应的模型属性).所以,我正在寻找一种方法来关闭password_confirmation检查/要求.

我发现这个答案提供了一个潜在的解决方案,但原始问题不同,我想单独验证它.它建议更新用户模型以添加以下内容:

class User < ActiveRecord::Base

  # ...

  has_secure_password validations: false
  validates :password, presence: true, length: { minimum: 6 }

end
Run Code Online (Sandbox Code Playgroud)

这似乎工作,并允许我的RSpec测试通过.我的两个问题是:

  1. 这种方法是否有任何负面后果或安全问题?
  2. Are there alternate ways to turn off password_confirmation that are safer or more inline with "The Ruby Way"?

keq*_*quc 10

ActiveModel :: SecurePassword有一个options参数,您可以指定不执行验证.

has_secure_password validations: false
Run Code Online (Sandbox Code Playgroud)

然后,只需确保手动对密码字段执行验证.

validates_presence_of :password, on: :create
Run Code Online (Sandbox Code Playgroud)

可选地,唯一缺少的是如果password_digest以某种方式为空,则引发错误.我不知道怎么会发生这种情况.

before_create { raise "Password digest missing on new record" if password_digest.blank? }
Run Code Online (Sandbox Code Playgroud)

在我看来,这似乎是尽可能干净地解决问题.


Jac*_*eve 2

如果您查看ActiveModel::SecurePassword,您将看到由 has_secure_password 创建的验证。

if options.fetch(:validations, true)
      validates_confirmation_of :password, if: :should_confirm_password?
      validates_presence_of     :password, on: :create
      validates_presence_of     :password_confirmation, if: :should_confirm_password?

      before_create { raise "Password digest missing on new record" if password_digest.blank? }
end
Run Code Online (Sandbox Code Playgroud)

通过禁用验证,您还可以阻止对字段的检查:password_digest,这不是一个大问题,但仍然不理想。

我认为更好的选择是覆盖默认方法,should_confirm_password?

# If password_confirmation is passed, business as usual.
# If not, don't run the validations
def should_confirm_password?
    password_confirmation.present? || false
end
Run Code Online (Sandbox Code Playgroud)