Skip to content

Instantly share code, notes, and snippets.

@mkessler
Created November 26, 2019 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkessler/ac2ca53e28437e2e71bea0d45552df2c to your computer and use it in GitHub Desktop.
Save mkessler/ac2ca53e28437e2e71bea0d45552df2c to your computer and use it in GitHub Desktop.
devise with scrypt || bcrypt hack
begin
require 'devise'
require 'devise/models/database_authenticatable'
begin
require 'bcrypt'
rescue LoadError
end
begin
require 'scrypt'
rescue LoadError
end
module Devise
def self.bcrypt(klass, password)
::BCrypt::Password.create("#{password}#{klass.pepper}", cost: klass.stretches).to_s
end if defined? BCrypt
def self.scrypt(klass, password)
::SCrypt::Password.create("#{password}#{klass.pepper}").to_s
end if defined? SCrypt
module Models
# Verifies whether an password (ie from sign in) is the user password.
def valid_password?(password)
return false if encrypted_password.blank?
if defined? SCrypt
scrypt = ::SCrypt::Password.new(encrypted_password)
password = ::SCrypt::Engine.hash_secret("#{password}#{self.class.pepper}", scrypt.cost + scrypt.salt)
elsif defined? BCrypt
bcrypt = ::BCrypt::Password.new(encrypted_password)
password = ::BCrypt::Engine.hash_secret("#{password}#{self.class.pepper}", bcrypt.salt)
else
fail 'Missing one of scrypt or bcrypt-ruby'
end
Devise.secure_compare(password, encrypted_password)
end
def authenticatable_salt
unless encrypted_password.blank?
if defined? SCrypt
password = ::SCrypt::Password.new(encrypted_password)
password.cost + password.salt
elsif defined? BCrypt
::BCrypt::Password.new(encrypted_password).salt
else
encrypted_password[0,29]
end
end
end
protected
# Digests the password using bcrypt. Custom encryption should override
# this method to apply their own algorithm.
#
# See https://github.com/plataformatec/devise-encryptable for examples
# of other encryption engines.
def password_digest(password)
if defined? SCrypt
Devise.scrypt(self.class, password)
elsif defined? BCrypt
Devise.bcrypt(self.class, password)
else
fail 'Missing scrypt or bcrypt gem for devise'
end
end
end
end
rescue LoadError
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment