Commit 3d17c2d7
Changed files (2)
app
models
spec
models
app/models/session.rb
@@ -4,6 +4,27 @@ class Session
def persisted?
end
- def self.login(username, password)
+ class << self
+ def login(username, password)
+ user = User.find_by(email: username)
+ return false if user.nil?
+ bcrypt = ::BCrypt::Password.new(user.encrypted_password)
+ password = ::BCrypt::Engine.hash_secret("#{password}#{User.pepper}", bcrypt.salt)
+ if secure_compare(password, user.encrypted_password)
+ #Session.create!(user: user)
+ else
+ false
+ end
+ end
+
+ # constant-time comparison algorithm to prevent timing attacks
+ def secure_compare(a, b)
+ return false if a.blank? || b.blank? || a.bytesize != b.bytesize
+ l = a.unpack "C#{a.bytesize}"
+
+ res = 0
+ b.each_byte { |byte| res |= byte ^ l.shift }
+ res == 0
+ end
end
end
spec/models/session_spec.rb
@@ -0,0 +1,21 @@
+require "rails_helper"
+
+describe Session do
+ describe ".login" do
+ context "when the email is not known" do
+ it "returns false" do
+ expect(Session.login('blah@example.com', 'password')).to be_falsey
+ end
+ end
+
+ context "when the email is known" do
+ let(:user) { create(:user) }
+
+ context "when the password is incorrect" do
+ it "returns false" do
+ expect(Session.login(user.email, 'blah')).to be_falsey
+ end
+ end
+ end
+ end
+end