2019-05-02 18:17:27 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2022-03-21 10:28:52 -04:00
|
|
|
require 'has_errors'
|
2016-09-22 14:31:10 -04:00
|
|
|
|
2020-11-10 05:09:15 -05:00
|
|
|
class Auth::GithubAuthenticator < Auth::ManagedAuthenticator
|
2013-08-23 02:20:43 -04:00
|
|
|
|
|
|
|
def name
|
|
|
|
"github"
|
|
|
|
end
|
|
|
|
|
2018-07-23 11:51:57 -04:00
|
|
|
def enabled?
|
|
|
|
SiteSetting.enable_github_logins
|
|
|
|
end
|
|
|
|
|
2018-07-27 12:18:53 -04:00
|
|
|
def after_authenticate(auth_token, existing_account: nil)
|
2020-11-10 05:09:15 -05:00
|
|
|
result = super
|
|
|
|
return result if result.user
|
|
|
|
# If email domain restrictions are configured,
|
|
|
|
# pick a secondary email which is allowed
|
|
|
|
all_github_emails(auth_token).each do |candidate|
|
|
|
|
next if !EmailValidator.allowed?(candidate[:email])
|
|
|
|
result.email = candidate[:email]
|
|
|
|
result.email_valid = !!candidate[:verified]
|
|
|
|
break
|
2018-07-27 12:18:53 -04:00
|
|
|
end
|
|
|
|
|
2020-11-10 05:09:15 -05:00
|
|
|
result
|
|
|
|
end
|
2016-09-22 14:31:10 -04:00
|
|
|
|
2020-11-10 05:09:15 -05:00
|
|
|
def find_user_by_email(auth_token)
|
|
|
|
# Use verified secondary emails to find a match
|
|
|
|
all_github_emails(auth_token).each do |candidate|
|
|
|
|
next if !candidate[:verified]
|
|
|
|
if user = User.find_by_email(candidate[:email])
|
|
|
|
return user
|
2016-09-22 14:31:10 -04:00
|
|
|
end
|
2013-08-23 02:20:43 -04:00
|
|
|
end
|
2020-11-10 05:09:15 -05:00
|
|
|
nil
|
2013-08-23 02:20:43 -04:00
|
|
|
end
|
|
|
|
|
2020-11-10 05:09:15 -05:00
|
|
|
def all_github_emails(auth_token)
|
|
|
|
emails = Array.new(auth_token[:extra][:all_emails])
|
|
|
|
primary_email = emails.find { |email| email[:primary] }
|
|
|
|
if primary_email
|
|
|
|
emails.delete(primary_email)
|
|
|
|
emails.unshift(primary_email)
|
|
|
|
end
|
|
|
|
emails
|
2013-08-23 02:20:43 -04:00
|
|
|
end
|
2013-08-25 21:04:16 -04:00
|
|
|
|
|
|
|
def register_middleware(omniauth)
|
|
|
|
omniauth.provider :github,
|
|
|
|
setup: lambda { |env|
|
|
|
|
strategy = env["omniauth.strategy"]
|
|
|
|
strategy.options[:client_id] = SiteSetting.github_client_id
|
|
|
|
strategy.options[:client_secret] = SiteSetting.github_client_secret
|
|
|
|
},
|
|
|
|
scope: "user:email"
|
|
|
|
end
|
2022-11-23 22:46:06 -05:00
|
|
|
|
|
|
|
# the omniauth-github gem only picks up the primary email if it's verified:
|
|
|
|
# https://github.com/omniauth/omniauth-github/blob/0ac46b59ccdabd4cbe5be4a665df269355081915/lib/omniauth/strategies/github.rb#L58-L61
|
|
|
|
def primary_email_verified?(auth_token)
|
|
|
|
true
|
|
|
|
end
|
2013-08-23 02:20:43 -04:00
|
|
|
end
|