"""Script update identity names in neo4j. Run this in dev with command PYTHONPATH=. env/bin/python3.6 dev/backfill_identity_names.py """ import csv import logging import json import os import sys import requests QA_ENVIRONMENT = 'qa' ENVIRONMENT = os.environ.get('Environment', QA_ENVIRONMENT) FILENAME = os.environ.get('FILENAME') OWS_USERS_BASE_URL = 'ows-users.theorchard.io' AUTH0_USER_DETAILS_URL = 'https://{env}-{base_url}/auth0/users/'.format( env=ENVIRONMENT, base_url=OWS_USERS_BASE_URL) IDENTITY_DETAILS_URL = 'https://{env}-{base_url}/users/identity/'.format( env=ENVIRONMENT, base_url=OWS_USERS_BASE_URL) log = logging.getLogger('main') log.setLevel(logging.DEBUG) fmt = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') sh = logging.StreamHandler(sys.stdout) sh.setFormatter(fmt) log.addHandler(sh) request_headers = { 'Content-Type': 'application/json' } def get_auth0_user_name(auth0_user_id): response = requests.get('{}{}'.format(AUTH0_USER_DETAILS_URL, auth0_user_id)) if response.status_code == 200: name = response.json()['name'] identity_id = response.json()['user_metadata']['orchardIdentityId'] return name, identity_id log.info('Failed fetching auth0 details.') def update_identity(auth0_user_name, identity_id): payload = json.dumps({'name': auth0_user_name}) response = requests.patch('{}{}'.format(IDENTITY_DETAILS_URL, identity_id), payload, headers=request_headers) log.info('Update identity response:{}'.format(response.text)) return response.status_code if __name__ == '__main__': log.info('Running identity update in neo4j for %s Environment', ENVIRONMENT) if not FILENAME: raise Exception('No file found.') log.info('Reading file %s from environment variables.', FILENAME) with open(FILENAME) as csv_file: reader = csv.DictReader(csv_file) for row in reader: auth0_user_id = row['auth0UserId'] backfill_status = 'FAILURE' log.info('Started backfill for %s', auth0_user_id) auth0_user_name, identity_id = get_auth0_user_name(auth0_user_id) or [None]*2 if auth0_user_name and identity_id: backfill_status=update_identity(auth0_user_name, identity_id) log.info('Ended backfill for {} with status {}'.format(auth0_user_id, backfill_status)) print('\n')