diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 9c6dcbf..852290e 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -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' diff --git a/app/models/authentication.rb b/app/models/authentication.rb index 2c69820..9977d77 100644 --- a/app/models/authentication.rb +++ b/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) @@ -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 diff --git a/spec/models/authentication_spec.rb b/spec/models/authentication_spec.rb index b45cb8b..98eeee9 100644 --- a/spec/models/authentication_spec.rb +++ b/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 @@ -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' }