Skip to content

Instantly share code, notes, and snippets.

@saiqulhaq
Created July 22, 2015 15:38
Show Gist options
  • Save saiqulhaq/60c0fe81e571a3cbf569 to your computer and use it in GitHub Desktop.
Save saiqulhaq/60c0fe81e571a3cbf569 to your computer and use it in GitHub Desktop.
require 'active_record'
require 'bcrypt'
class User < ActiveRecord::Base
PASSWORD_SALT = '$2a$20$ESQ40HbYj00QFse2rbArOe'.freeze
PASSWORD_COST = 15.freeze
establish_connection adapter: 'sqlite3', database: ':memory:'
connection.create_table table_name, force: true do |t|
t.string :email
t.string :password
end
validates :email, uniqueness: true
validates :email, :password, presence: true
before_create :validate_password
attr_accessor :password_confirmation
def password=(password)
@original_password = password
super ::BCrypt::Password.create(password + PASSWORD_SALT, cost: PASSWORD_COST)
end
def password_confirmation=(password)
@password_confirmation = password
end
private
def validate_password
if @original_password.to_s == @password_confirmation.to_s
true
else
raise 'Password mismatch'
end
end
def self.authenticate params
user = User.find_by_email params[:email]
return false unless user.present?
password = ::BCrypt::Password.new user.password
return password == (params[:password] + PASSWORD_SALT) if password.present?
false
end
end
# Now we create an user
User.create email: '[email protected]', password: 'pass', password_confirmation: 'pass'
# And assume this is a form data submitted by user
login_params = { email: '[email protected]', password: 'pass'}
puts User.authenticate login_params #=> true
login_params = { email: '[email protected]', password: 'word'}
puts User.authenticate login_params #=> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment