Skip to content

Instantly share code, notes, and snippets.

@mtbdeano
Created December 9, 2015 01:01
Show Gist options
  • Save mtbdeano/8a8be011ba4fc35be062 to your computer and use it in GitHub Desktop.
Save mtbdeano/8a8be011ba4fc35be062 to your computer and use it in GitHub Desktop.
Gist to force users from old Google apps domain to new domain (after domain rename)
from __future__ import print_function
import httplib2
import os
import json
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/admin.directory.user'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Directory API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'admin-directory_v1-python-quickstart.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
"""
Manually rename users from old domain into new domain
"""
OLD_DOMAIN = 'l2thinktank.com'
NEW_DOMAIN = 'l2inc.com'
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('admin', 'directory_v1', http=http)
print('Getting the first 10 users in the domain')
results = service.users().list(customer='my_customer',
domain=OLD_DOMAIN,
orderBy='email').execute()
users = results.get('users', [])
if not users:
print('No users in the domain.')
else:
print('Users:')
for user in users:
old_email = user['primaryEmail']
account = old_email.split('@')[0]
new_email = '{}@{}'.format(account, NEW_DOMAIN)
print('{} {} to {}'.format(user['id'], old_email, new_email))
ret = service.users().patch(userKey=user['id'],
body={'primaryEmail': new_email})
ret.execute()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment