2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2022-03-21 22:28:52 +08:00
|
|
|
require "has_errors"
|
2016-09-23 02:31:10 +08:00
|
|
|
|
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
|
2022-11-24 11:46:06 +08: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 14:20:43 +08:00
|
|
|
end
|