Created
July 11, 2022 07:58
-
-
Save RobertKim/574e0b20cbed0a3ebeaf10e7ebae3e28 to your computer and use it in GitHub Desktop.
Code sample - connection to Google Cloud Platform API for Adming directory user creation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'google/apis/admin_directory_v1' | |
require 'googleauth' | |
module GoogleIntegration | |
class EmailAccountCreator | |
def initialize(account) | |
@account = account | |
end | |
def call | |
begin | |
service = service_account | |
user_object = configured_user_object | |
service.insert_user(user_object) | |
@account.update!(internal_email: email_string) | |
rescue => e | |
puts "#{Time.now.in_time_zone('Mountain Time (US & Canada)')} | email_account_creator - Error: #{e.message}" | |
end | |
end | |
private | |
def service_account | |
service = Google::Apis::AdminDirectoryV1::DirectoryService.new | |
service.client_options.application_name = "tomarket production" | |
@g_scopes = [Google::Apis::AdminDirectoryV1::AUTH_ADMIN_DIRECTORY_USER, Google::Apis::AdminDirectoryV1::AUTH_ADMIN_DIRECTORY_USER_ALIAS] | |
@config = { | |
client_email: ENV['GOOGLE_TOMARKET_CLIENT_EMAIL'], | |
client_id: ENV['GOOGLE_TOMARKET_CLIENT_ID'], | |
private_key_id: ENV['GOOGLE_TOMARKET_PRIVATE_KEY_ID'], | |
private_key: ENV['GOOGLE_TOMARKET_PRIVATE_KEY'], | |
type: "service_account" | |
} | |
service.authorization =Google::Auth::ServiceAccountCredentials.make_creds( | |
scope: @g_scopes, | |
json_key_io: StringIO.new(@config.to_json, 'r') | |
) | |
authorization = service.authorization | |
auth_client = authorization.dup | |
auth_client.sub = ENV['TOMARKET_ADMIN_EMAIL'] | |
auth_client.fetch_access_token! | |
service.authorization = auth_client | |
service | |
end | |
def configured_user_object | |
Google::Apis::AdminDirectoryV1::User.new( | |
name: { | |
given_name: @account.name, | |
family_name: @account.name, | |
full_name: @account.name | |
}, | |
password: ENV['GOOGLE_TOMARKET_MASTER_GMAIL_PASSWORD'], | |
primary_email: email_string | |
) | |
end | |
def email_string | |
@account.name.downcase.gsub(" ","").gsub(/\W/,'') + "@tomarket.farm" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment