【问题标题】:Rails 4 'has_secure_password' validates a blank password and cannot perform conditional validationsRails 4 'has_secure_password' 验证空白密码并且无法执行条件验证
【发布时间】:2014-04-15 17:02:39
【问题描述】:

我知道 has_secure_password 在 :create 操作中添加了密码和密码确认验证。

当您创建一个新用户时,您必须输入密码(和确认),否则该用户无效。这是预期的行为,很好。

当您想要更新用户时,您可以更新选择属性,而无需提交密码/确认。这也很好,因为我可以更新用户名而无需密码。

但是,我遇到了一种情况,我想更新用户的密码,我要求用户输入他们当前的密码,然后输入他们的新密码并确认。问题是当我只输入当前密码并提交表单时,它通过了所有验证。尽管这可能是预期的行为,但我认为这是一个非常糟糕的行为,因为密码不会更改为空白值,即使它通过了所有验证。如果我只是假设代码实际上按照“说”的那样做,那么用户现在应该有一个空白密码。

class User < ActiveRecord::Base
  # model has password_digest field
  has_secure_password

  # has_secure_password automatically adds the following...
  # validates :password, presence: true, on: [:create]

  validates :password, length: { minimum: 8 }
end

class SettingsController < ApplicationController
  # POSTed from form with fields :current_password, :new_password, :new_password_confirmation
  def update_password
    if current_user.authenticate(params[:current_password])
      if current_user.update_attributes(password: params[:new_password], password_confirmation: params[:new_password_confirmation])
        flash.now[:notice] = "Successfully updated Password"
      else
        # Problem with new password (do nothing)
        flash.now[:error] = "Invalid new password or confirmation (nothing changed)"
        render "error"
      end
    else
      flash.now[:error] = "Must provide current password to change your password"
      render "error"
    end
  end
end

如果您正确输入了 current_password 但将 new_password 和 new_password_confirmation 留空,控制器代码会愉快地通知用户“密码更新成功”。

但是用户没有更新。密码未设置为空白值。它没有改变。

我尝试设置密码验证条件,但我的尝试似乎都没有奏效。我要做的是每次在表单中提交密码字段时验证密码的存在和长度(即使它是空白的)。我用谷歌搜索了这个,我读过的例子都没有。

必须有一个不会破解的标准解决方案。所需的功能是每次在表单中提交密码字段时,都应运行密码验证并验证密码是否为空、满足最小长度要求等...

我看到很多人说这些有效,但似乎没有一个真正有效:

validates :password, length: ( minimum: 8 }, if: -> { password.present? }
validates :password, length: ( minimum: 8 }, allow_nil: true

【问题讨论】:

  • 我遇到了同样的问题。看来,最终,has_secure_password 添加的 password 虚拟属性无法分配空字符串。如果你这样做了,它仍然是nil,让验证愉快地通过。
  • @Franco,我也没有找到好的解决方案。我终于在我的控制器中进行了new_password.blank? 检查,然后在页面为空白时呈现错误页面。它有效,但它是目前 Rails 中的“陷阱”之一。

标签: validation ruby-on-rails-4 passwords bcrypt


【解决方案1】:

当且仅当密码和password_confirmation 为空时,存在允许密码为空的验证。因此,如果您尝试更新密码并且不发送密码确认,则会引发错误。

试试这个:

validates :password, length: { minimum: 8 }, allow_blank: true

【讨论】:

    猜你喜欢
    • 2019-08-13
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 2014-08-16
    • 2012-05-06
    相关资源
    最近更新 更多