2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-09-23 02:31:10 +08:00
|
|
|
require_dependency 'has_errors'
|
|
|
|
|
2020-11-10 18:09:15 +08:00
|
|
|
class Auth::GithubAuthenticator < Auth::ManagedAuthenticator
|
2013-08-23 14:20:43 +08:00
|
|
|
|
|
|
|
def name
|
|
|
|
"github"
|
|
|
|
end
|
|
|
|
|
2018-07-23 23:51:57 +08:00
|
|
|
def enabled?
|
|
|
|
SiteSetting.enable_github_logins
|
|
|
|
end
|
|
|
|
|
2018-07-28 00:18:53 +08:00
|
|
|
def after_authenticate(auth_token, existing_account: nil)
|
2020-11-10 18:09:15 +08: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-28 00:18:53 +08:00
|
|
|
end
|
|
|
|
|
2020-11-10 18:09:15 +08:00
|
|
|
result
|
|
|
|
end
|
2016-09-23 02:31:10 +08:00
|
|
|
|
2020-11-10 18:09:15 +08: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-23 02:31:10 +08:00
|
|
|
end
|
2013-08-23 14:20:43 +08:00
|
|
|
end
|
2020-11-10 18:09:15 +08:00
|
|
|
nil
|
2013-08-23 14:20:43 +08:00
|
|
|
end
|
|
|
|
|
2020-11-10 18:09:15 +08: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 14:20:43 +08:00
|
|
|
end
|
2013-08-26 09:04:16 +08: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
|
2013-08-23 14:20:43 +08:00
|
|
|
end
|