Skip to content

Instantly share code, notes, and snippets.

@rbclark
Created May 17, 2023 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbclark/9143dd3e21087c21d7f63ffc9e9fa76c to your computer and use it in GitHub Desktop.
Save rbclark/9143dd3e21087c21d7f63ffc9e9fa76c to your computer and use it in GitHub Desktop.
List all users in a Google Admin Directory
require 'google/apis/admin_directory_v1'
require 'googleauth'
require 'googleauth/stores/file_token_store'
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
APPLICATION_NAME = 'Google Admin Directory API Ruby Quickstart'
CLIENT_SECRETS_PATH = 'client_secret.json'
CREDENTIALS_PATH = File.join(Dir.home, '.credentials',
"admin-directory_v1-ruby-quickstart.yaml")
def authorize
scope = ["https://www.googleapis.com/auth/admin.directory.user.readonly"]
client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)
authorizer = Google::Auth::UserAuthorizer.new(client_id, scope, token_store)
user_id = ENV['USER']
credentials = authorizer.get_credentials(user_id)
if credentials.nil?
url = authorizer.get_authorization_url(base_url: OOB_URI)
puts "Open #{url} in your browser and enter the resulting code:"
code = gets
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI)
end
credentials
end
# Initialize the API
Admin = Google::Apis::AdminDirectoryV1 # Alias the module
service = Admin::DirectoryService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
response = service.list_users(customer: 'my_customer')
puts "Users:"
puts "No users found" if response.users.empty?
response.users.each { |user| puts "- #{user.primary_email}" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment