Skip to content

Instantly share code, notes, and snippets.

@henrik
Created September 10, 2013 14:24
Show Gist options
  • Save henrik/6510138 to your computer and use it in GitHub Desktop.
Save henrik/6510138 to your computer and use it in GitHub Desktop.
A precursor of http://github.com/henrik/autho. Simple Rails-less authentication model. Assumes an API compatible with ActiveRecord and Rails' has_secure_password.
require "bcrypt"
require "attr_extras"
class Authentication
pattr_initialize :finder, :email, :password
def self.digest(unencrypted_password)
BCrypt::Password.create(unencrypted_password)
end
def user
user = finder.find_by_email(email)
user && authenticate(user, password)
end
private
def authenticate(user, unencrypted_password)
if BCrypt::Password.new(user.password_digest) == unencrypted_password
user
else
nil
end
end
end
require "spec_helper"
describe Authentication do
describe "#user" do
let(:finder) { double }
it "returns the user with matching email and password" do
user = double(password_digest: digest("sesame"))
expect(finder).to receive(:find_by_email).with("user@example.com").and_return(user)
auth = Authentication.new(finder, "user@example.com", "sesame")
expect(auth.user).to eq user
end
it "finds nothing if email does not match" do
expect(finder).to receive(:find_by_email).with("user@example.com").and_return(nil)
auth = Authentication.new(finder, "user@example.com", "sesame")
expect(auth.user).to be_nil
end
it "finds nothing if password does not match" do
user = double(password_digest: digest("sesame"))
expect(finder).to receive(:find_by_email).with("user@example.com").and_return(user)
auth = Authentication.new(finder, "user@example.com", "nomagic")
expect(auth.user).to be_nil
end
end
def digest(unencrypted_password)
BCrypt::Password.create(unencrypted_password)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment