Skip to content

Instantly share code, notes, and snippets.

@pda
Forked from dmateos/gist:2446c737e8c64a15170b
Last active February 11, 2016 20:31
Show Gist options
  • Save pda/c92e555dbc16d95d1edb to your computer and use it in GitHub Desktop.
Save pda/c92e555dbc16d95d1edb to your computer and use it in GitHub Desktop.
require "bcrypt"
module GoTipping
class UserAuthenticator
def initialize(organisation, username, finder)
@organisation = organisation
@username = username
@finder = finder
end
def authenticate(password)
return false unless user
if BCrypt::Password.new(user.password_digest) == password
user
else
false
end
end
private
def user
@_user ||= @finder.by_organisation_and_username(@organisation, @username)
end
end
class UserFinder
def by_organisation_and_username(organisation, username)
organization.users.find_by(username: username)
end
end
end
require_relative "gistfile1"
RSpec.describe GoTipping::UserAuthenticator do
subject { described_class.new(organisation, username, finder) }
let(:username) { "foo" }
let(:finder) { instance_double(GoTipping::UserFinder) }
let(:organisation) { double("Organization") }
let(:user) { double("User", password_digest: digest) }
let(:digest) { "$2a$10$jYOHOwYW6PcYGUG6IafkV.WAqFY86sfkzjqOxxmycp7UozxXRr5ia" }
before do
expect(finder).to receive(:by_organisation_and_username).
with(organisation, username).
and_return(user)
end
context "user not found" do
let(:user) { nil }
it "is false" do
expect(subject.authenticate("foo")).to eq(false)
end
end
context "password wrong" do
it "is false" do
expect(subject.authenticate("wrong")).to eq(false)
end
end
context "password correct" do
it "returns the user" do
expect(subject.authenticate("right")).to eq(user)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment