如何在rails中使用bcrypt并验证密码?

时间:2013-09-03 03:19:25

标签: ruby-on-rails bcrypt

由于rails在保存期间清除了错误,我无法在我的模型中执行此操作:

  def password= plain_text
    if plain_text =~ /\d/ && plain_text =~ /\w/
      self.password_digest = BCrypt::Password.create(plain_text)
    else
      self.errors[:password] = "must contain one digit and one word character."
    end
  end

验证密码的最佳方法是什么是在rails中使用一个字母和一个数字,同时仍然使用bcrypt?

1 个答案:

答案 0 :(得分:0)

如果您正在使用Rails has_secure_password选项,那么Rails将为您处理password=方法。设置密码Rails will hold onto the unencrypted password in the instance variable @password时:

def password=(unencrypted_password)
  ...
  @password = unencrypted_password
  cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
  self.password_digest = BCrypt::Password.create(unencrypted_password, cost: cost)

@password值将保留在内存中,直到将记录保存到数据库中为止。因此,您可以针对password运行验证。验证通过时,将存储加密的password_digest值。

您可以看到Rails validate that the password isn't longer than the largest password allowed所做的事情:

validates_length_of :password, maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED