discourse/lib/auth/omniauth_strategies/discourse_google_oauth2.rb
Angus McLeod df3886d6e5
FEATURE: Experimental support for group membership via google auth (#14835)
This commit introduces a new site setting "google_oauth2_hd_groups". If enabled, group information will be fetched from Google during authentication, and stored in the Discourse database. These 'associated groups' can be connected to a Discourse group via the "Membership" tab of the group preferences UI. 

The majority of the implementation is generic, so we will be able to add support to more authentication methods in the near future.

https://meta.discourse.org/t/managing-group-membership-via-authentication/175950
2021-12-09 12:30:27 +00:00

46 lines
1.2 KiB
Ruby

# frozen_string_literal: true
class Auth::OmniAuthStrategies
class DiscourseGoogleOauth2 < OmniAuth::Strategies::GoogleOauth2
GROUPS_SCOPE ||= "admin.directory.group.readonly"
GROUPS_DOMAIN ||= "admin.googleapis.com"
GROUPS_PATH ||= "/admin/directory/v1/groups"
def extra
hash = {}
hash[:raw_info] = raw_info
hash[:raw_groups] = raw_groups if options[:request_groups]
hash
end
def raw_groups
@raw_groups ||= begin
groups = []
page_token = nil
groups_url = "https://#{GROUPS_DOMAIN}#{GROUPS_PATH}"
loop do
params = {
userKey: uid
}
params[:pageToken] = page_token if page_token
response = access_token.get(groups_url, params: params, raise_errors: false)
if response.status == 200
response = response.parsed
groups.push(*response['groups'])
page_token = response['nextPageToken']
break if page_token.nil?
else
Rails.logger.error("[Discourse Google OAuth2] failed to retrieve groups for #{uid} - status #{response.status}")
break
end
end
groups
end
end
end
end