Skip to content

Commit d8da8b0

Browse files
committed
Merge pull request #22 from kenn/primary_email
email field now returns the user's primary email.
2 parents b096262 + 9fda2d3 commit d8da8b0

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

lib/omniauth/strategies/github.rb

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,19 @@ def raw_info
4646
end
4747

4848
def email
49-
raw_info['email'] || (email_access_allowed? ? emails.first : nil)
49+
raw_info['email'] || primary_email
5050
end
5151

52+
def primary_email
53+
primary = emails.find{|i| i['primary'] }
54+
primary && primary['email'] || emails.first && emails.first['email']
55+
end
56+
57+
# The new /user/emails API - http://developer.github.com/v3/users/emails/#future-response
5258
def emails
59+
return [] unless email_access_allowed?
5360
access_token.options[:mode] = :query
54-
@emails ||= access_token.get('/user/emails').parsed
61+
@emails ||= access_token.get('/user/emails', :headers => { 'Accept' => 'application/vnd.github.v3' }).parsed
5562
end
5663

5764
def email_access_allowed?

spec/omniauth/strategies/github_spec.rb

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,11 +57,26 @@
5757
subject.email.should be_nil
5858
end
5959

60+
it "should return the primary email if there is no raw_info and email access is allowed" do
61+
emails = [
62+
{ 'email' => 'secondary@example.com', 'primary' => false },
63+
{ 'email' => 'primary@example.com', 'primary' => true }
64+
]
65+
subject.stub!(:raw_info).and_return({})
66+
subject.options['scope'] = 'user'
67+
subject.stub!(:emails).and_return(emails)
68+
subject.email.should eq('primary@example.com')
69+
end
70+
6071
it "should return the first email if there is no raw_info and email access is allowed" do
72+
emails = [
73+
{ 'email' => 'first@example.com', 'primary' => false },
74+
{ 'email' => 'second@example.com', 'primary' => false }
75+
]
6176
subject.stub!(:raw_info).and_return({})
6277
subject.options['scope'] = 'user'
63-
subject.stub!(:emails).and_return([ 'you@example.com' ])
64-
subject.email.should eq('you@example.com')
78+
subject.stub!(:emails).and_return(emails)
79+
subject.email.should eq('first@example.com')
6580
end
6681
end
6782

0 commit comments

Comments
 (0)