Skip to content

Instantly share code, notes, and snippets.

@thomaswitt
Created November 14, 2013 14:54
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomaswitt/7468182 to your computer and use it in GitHub Desktop.
Save thomaswitt/7468182 to your computer and use it in GitHub Desktop.
Access Google Apps Admin SDK Directory API and retrieve all users from Google Apps
#!/usr/bin/env ruby
require 'rubygems'
require 'json'
require 'google/api_client'
require 'active_support/core_ext/hash'
# 1. Go to Google Cloud Console (https://cloud.google.com/console)
# 2. Create Service Account with P12 File
# 3. Enable the Admin SDK in APIs.
# 4. Create a Project
# 5. Create a registered app within this project
# 6. Go to section 'Certificate' and generate a key
# 7. Download the JSON file as well
# 8. Go to the Apps Console > Security > Extended > 3rdPartgy OAuth
# (https://admin.google.com/AdminHome?#OGX:ManageOauthClients)
# 9. Add a API Client. Client name is value of client_id in the JSON
# file, API Scope is https://www.googleapis.com/auth/admin.directory.user.readonly
# The value of client_email from the JSON file goes here
SERVICE_ACCOUNT_EMAIL = '00000000-abcdef@developer.gserviceaccount.com'
# This should be an Admin
ACT_ON_BEHALF_EMAIL = 'john.doe@company.com'
# File path to the certificate
SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'client.p12'
key = Google::APIClient::PKCS12.load_key(
SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'notasecret')
asserter = Google::APIClient::JWTAsserter.new(SERVICE_ACCOUNT_EMAIL,
'https://www.googleapis.com/auth/admin.directory.user.readonly', key)
client = Google::APIClient.new(:application_name =>
'rubyapp.company.com')
client.authorization = asserter.authorize(ACT_ON_BEHALF_EMAIL)
api = client.discovered_api('admin', 'directory_v1')
result = client.execute(
:api_method => api.users.list,
:parameters => {
'domain' => 'company.com',
'orderBy' => 'givenName',
'maxResults' => 500,
'fields' => 'users(id,etag,primaryEmail,name,suspended)',
}
)
users = JSON.parse(result.body, {:symbolize_names => true})[:users]
users.each do |u|
puts "#{u[:name][:fullName]} <#{u[:primaryEmail]}>
end
@thomaswitt
Copy link
Author

if you want to use an RSA key instead of p12, use:

key = OpenSSL::PKey::RSA.new(GOOGLE_APPS_KEY_AS_STRING)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment