0

我试图了解如何has_secure_password工作。在 bcrypt-ruby网站上有以下示例说明如何使用它。password上课的方法User让我很困惑。看起来代码@password ||= Password.new(password_hash)采用加密的哈希并返回未加密的密码。仅从加密的哈希中恢复密码是不可能的。我在误解什么Password.new

用户模型

require 'bcrypt'

class User < ActiveRecord::Base
  # users.password_hash in the database is a :string
  include BCrypt

  def password
    @password ||= Password.new(password_hash)
  end

  def password=(new_password)
    @password = Password.create(new_password)
    self.password_hash = @password
  end
end

创建帐户

def create
  @user = User.new(params[:user])
  @user.password = params[:password]
  @user.save!
end

验证用户

def login
  @user = User.find_by_email(params[:email])
  if @user.password == params[:password]
    give_token
  else
    redirect_to home_url
  end
end
4

1 回答 1

0

I figured out that the line of code if @user.password == params[:password] is not comparing the encrypted hash with the unencrypted password params[:password]. It takes params[:password] and hashes it before doing a comparison. The hashing of params[:password] is obscured by == which turns out to be a method call.

于 2013-03-30T05:23:12.963 回答