Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Split out BCrypt hashing to make it reusable
This logic is generic and reusable -- hash a secret; and take an unhashed secret and compare it to a hashed secret. This breaks this out to make it reusable in other places. Specifically, we use this in our own token auth at Bonobos that we plan to split out as a Devise extension. This will make that possible without copy & pasting this code.
- Loading branch information
Showing
3 changed files
with
29 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
require 'bcrypt' | ||
|
||
module Devise | ||
module Encryptor | ||
def self.digest(klass, password) | ||
if klass.pepper.present? | ||
password = "#{password}#{klass.pepper}" | ||
end | ||
::BCrypt::Password.create(password, cost: klass.stretches).to_s | ||
end | ||
|
||
def self.compare(klass, encrypted_password, password) | ||
This comment has been minimized.
Sorry, something went wrong. |
||
return false if encrypted_password.blank? | ||
bcrypt = ::BCrypt::Password.new(encrypted_password) | ||
if klass.pepper.present? | ||
password = "#{password}#{klass.pepper}" | ||
end | ||
password = ::BCrypt::Engine.hash_secret(password, bcrypt.salt) | ||
Devise.secure_compare(password, encrypted_password) | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Why pass the klass instead of the pepper?