Skip to content

Commit

Permalink
Refactor to Authentication.find_or_create_person
Browse files Browse the repository at this point in the history
  • Loading branch information
mattyoho committed Mar 2, 2012
1 parent 1bfa3bd commit 8d71bf7
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 11 deletions.
2 changes: 1 addition & 1 deletion app/controllers/sessions_controller.rb
Expand Up @@ -8,7 +8,7 @@ def new

def create
auth = request.env['omniauth.auth']
person = Authentication.person(auth)
person = Authentication.find_or_create_person(auth)
session[:user_id] = person.id

redirect_to root_path, :notice => 'Logged in successfully'
Expand Down
11 changes: 7 additions & 4 deletions app/models/authentication.rb
@@ -1,10 +1,8 @@
class Authentication < ActiveRecord::Base
belongs_to :person

def self.person(credentials)
if auth = find_by_provider_and_uid(credentials['provider'], credentials['uid']) then
person = auth.person
else
def self.find_or_create_person(credentials)
unless person = find_person(credentials['provider'], credentials['uid']) then
info = credentials['info']
first_name, *_, last_name = info['name'].split.map(&:strip)

Expand All @@ -19,4 +17,9 @@ def self.person(credentials)

person
end

def self.find_person(provider, uid)
auth = where(provider: provider, uid: uid).includes(:person).first
auth && auth.person
end
end
12 changes: 6 additions & 6 deletions spec/models/authentication_spec.rb
@@ -1,14 +1,14 @@
require 'spec_helper'

describe Authentication do
describe ".person" do
describe ".find_or_create_person" do
context "when the person has authenticated previously" do
let!(:auth) { Factory(:authentication, provider: 'github', uid: 'abc123') }
let(:person) { auth.person }

it "finds that person by provider credentials" do
creds = {'provider' => 'github', 'uid' => 'abc123'}
Authentication.person(creds).should == person
Authentication.find_or_create_person(creds).should == person
end
end

Expand All @@ -18,20 +18,20 @@
end

it "creates a person record for them using info" do
expect { Authentication.person(creds) }.to change { Person.count }.by(1)
expect { Authentication.find_or_create_person(creds) }.to change { Person.count }.by(1)
end

it "creates an auth record for future logins" do
expect do
Authentication.person(creds)
Authentication.person(creds)
Authentication.find_or_create_person(creds)
Authentication.find_or_create_person(creds)
end.to change { Person.count }.by(1)
end

describe "creating the person record" do
subject do
creds['info'] = {'name' => 'Octo Cat', 'nickname' => 'octocat', 'email' => 'octocat@hungryacademy.com'}
Authentication.person(creds)
Authentication.find_or_create_person(creds)
end

its(:first_name) { should == 'Octo' }
Expand Down

0 comments on commit 8d71bf7

Please sign in to comment.