0

I am trying to understand how has_secure_password works. On the bcrypt-ruby website has the following below examples of how to use it. The password method of class User confuses me. It looks like the code @password ||= Password.new(password_hash) takes the encrypted hash and gives back the unencrypted password. It shouldn't be possible to recover the password from just the encrypted hash. What am I misunderstanding about Password.new

The User model

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

Creating an account

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

Authenticating a user

def login
  @user = User.find_by_email(params[:email])
  if @user.password == params[:password]
    give_token
  else
    redirect_to home_url
  end
end
user782220
  • 10,677
  • 21
  • 72
  • 135

1 Answers1

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.

user782220
  • 10,677
  • 21
  • 72
  • 135