diff --git a/src/gam/__init__.py b/src/gam/__init__.py index 2ca4ff13..ef084f43 100755 --- a/src/gam/__init__.py +++ b/src/gam/__init__.py @@ -887,8 +887,7 @@ def doGAMVersion(checkForArgs=True): for lib in GAM_VER_LIBS: try: print(f'{lib} {lib_version(lib)}') - except Exception as e: - print(e) + except: pass tls_ver, cipher_name, used_ip = _getServerTLSUsed(testLocation) print( @@ -1133,39 +1132,66 @@ def buildGAPIObjectNoAuthentication(api): service = getService(api, httpObj) return service -# Convert UID to email address +def get_user_email_from_id(uid, cd): + try: + result = gapi.call( + cd.users(), + 'get', + throw_reasons=[gapi_errors.ErrorReason.USER_NOT_FOUND], + userKey=uid, + fields='primaryEmail') + return result.get('primaryEmail') + except gapi_errors.GapiUserNotFoundError: + return + +def get_group_email_from_id(uid, cd): + try: + result = gapi.call( + cd.groups(), + 'get', + throw_reasons=[gapi_errors.ErrorReason.GROUP_NOT_FOUND], + groupKey=uid, + fields='email') + return result.get('email') + except gapi_errors.GapiGroupNotFoundError: + return + def convertUIDtoEmailAddress(emailAddressOrUID, cd=None, email_types=['user']): + '''convert UID to email address + returns email address and object type''' if isinstance(email_types, str): email_types = email_types.split(',') normalizedEmailAddressOrUID = normalizeEmailAddressOrUID(emailAddressOrUID) if normalizedEmailAddressOrUID.find('@') > 0: - return normalizedEmailAddressOrUID + return normalizedEmailAddressOrUID, 'email' if not cd: cd = buildGAPIObject('directory') - if 'user' in email_types: - try: - result = gapi.call( - cd.users(), - 'get', - throw_reasons=[gapi_errors.ErrorReason.USER_NOT_FOUND], - userKey=normalizedEmailAddressOrUID, - fields='primaryEmail') - if 'primaryEmail' in result: - return result['primaryEmail'].lower() - except gapi_errors.GapiUserNotFoundError: - pass - if 'group' in email_types: - try: - result = gapi.call( - cd.groups(), - 'get', - throw_reasons=[gapi_errors.ErrorReason.GROUP_NOT_FOUND], - groupKey=normalizedEmailAddressOrUID, - fields='email') - if 'email' in result: - return result['email'].lower() - except gapi_errors.GapiGroupNotFoundError: - pass + if 'user' in email_types and 'group' in email_types: + # Google User IDs *TEND* to be integers while groups tend to have letters + # thus we can optimize which check we try first. We'll still check + # both since there is no guarantee this will always be true. + if normalizedEmailAddressOrUID.isdigit(): + uid = get_user_email_from_id(normalizedEmailAddressOrUID, cd) + if uid: + return uid, 'user' + uid = get_group_email_from_id(normalizedEmailAddressOrUID, cd) + if uid: + return uid, 'group' + else: + uid = get_group_email_from_id(normalizedEmailAddressOrUID, cd) + if uid: + return uid, 'group' + uid = get_user_email_from_id(normalizedEmailAddressOrUID, cd) + if uid: + return uid, 'user' + elif 'user' in email_types: + uid = get_user_email_from_id(normalizedEmailAddressOrUID, cd) + if uid: + return uid, 'user' + elif 'group' in email_types: + uid = get_group_email_from_id(normalizedEmailAddressOrUID, cd) + if uid: + return uid, 'group' if 'resource' in email_types: try: result = gapi.call( @@ -1176,10 +1202,10 @@ def convertUIDtoEmailAddress(emailAddressOrUID, cd=None, email_types=['user']): customer=GC_Values[GC_CUSTOMER_ID], fields='resourceEmail') if 'resourceEmail' in result: - return result['resourceEmail'].lower() + return result['resourceEmail'].lower(), 'resource' except gapi_errors.GapiResourceNotFoundError: pass - return normalizedEmailAddressOrUID + return normalizedEmailAddressOrUID, 'unknown' # Convert email address to UID @@ -1193,12 +1219,13 @@ def convertEmailAddressToUID(emailAddressOrUID, cd=None, email_type='user'): result = gapi.call( cd.users(), 'get', - throw_reasons=[gapi_errors.ErrorReason.USER_NOT_FOUND], + throw_reasons=[gapi_errors.ErrorReason.USER_NOT_FOUND, + gapi_errors.ErrorReason.BAD_REQUEST], userKey=normalizedEmailAddressOrUID, fields='id') if 'id' in result: return result['id'] - except gapi_errors.GapiUserNotFoundError: + except (gapi_errors.GapiUserNotFoundError, gam.gapi.errors.GapiBadRequestError): pass try: result = gapi.call( @@ -1250,27 +1277,27 @@ def buildGAPIServiceObject(api, act_as, showAuthError=True, scopes=None): def buildAlertCenterGAPIObject(user): - userEmail = convertUIDtoEmailAddress(user) + userEmail, _ = convertUIDtoEmailAddress(user) return (userEmail, buildGAPIServiceObject('alertcenter', userEmail)) def buildActivityGAPIObject(user): - userEmail = convertUIDtoEmailAddress(user) + userEmail, _ = convertUIDtoEmailAddress(user) return (userEmail, buildGAPIServiceObject('driveactivity', userEmail)) def buildDriveGAPIObject(user): - userEmail = convertUIDtoEmailAddress(user) + userEmail, _ = convertUIDtoEmailAddress(user) return (userEmail, buildGAPIServiceObject('drive', userEmail)) def buildDrive3GAPIObject(user): - userEmail = convertUIDtoEmailAddress(user) + userEmail, _ = convertUIDtoEmailAddress(user) return (userEmail, buildGAPIServiceObject('drive3', userEmail)) def buildGmailGAPIObject(user): - userEmail = convertUIDtoEmailAddress(user) + userEmail, _ = convertUIDtoEmailAddress(user) return (userEmail, buildGAPIServiceObject('gmail', userEmail)) @@ -2294,7 +2321,7 @@ def doGetCourseInfo(): croom = buildGAPIObject('classroom') courseId = addCourseIdScope(sys.argv[3]) info = gapi.call(croom.courses(), 'get', id=courseId) - info['ownerEmail'] = convertUIDtoEmailAddress(f'uid:{info["ownerId"]}') + info['ownerEmail'], _ = convertUIDtoEmailAddress(f'uid:{info["ownerId"]}') display.print_json(info) teachers = gapi.get_all_pages(croom.courses().teachers(), 'list', @@ -2479,7 +2506,7 @@ def doPrintCourses(): if ownerEmails is not None: ownerId = course['ownerId'] if ownerId not in ownerEmails: - ownerEmails[ownerId] = convertUIDtoEmailAddress(f'uid:{ownerId}', + ownerEmails[ownerId], _ = convertUIDtoEmailAddress(f'uid:{ownerId}', cd=cd) course['ownerEmail'] = ownerEmails[ownerId] for field in skipFieldsList: diff --git a/src/gam/gapi/calendar.py b/src/gam/gapi/calendar.py index 21845ce9..917e3e2f 100644 --- a/src/gam/gapi/calendar.py +++ b/src/gam/gapi/calendar.py @@ -18,9 +18,9 @@ def normalizeCalendarId(calname, checkPrimary=False): return calname if not GC_Values[GC_DOMAIN]: GC_Values[GC_DOMAIN] = gam._getValueFromOAuth('hd') - return gam.convertUIDtoEmailAddress(calname, + email, _ = gam.convertUIDtoEmailAddress(calname, email_types=['user', 'resource']) - + return email def buildCalendarGAPIObject(calname): calendarId = normalizeCalendarId(calname) diff --git a/src/gam/gapi/cloudidentity/groups.py b/src/gam/gapi/cloudidentity/groups.py index 5908cb6c..f2e401f2 100644 --- a/src/gam/gapi/cloudidentity/groups.py +++ b/src/gam/gapi/cloudidentity/groups.py @@ -230,7 +230,7 @@ def print_(): todrive = True i += 1 elif myarg == 'enterprisemember': - member = gam.convertUIDtoEmailAddress(sys.argv[i + 1], email_types=['user', 'group']) + member, _ = gam.convertUIDtoEmailAddress(sys.argv[i + 1], email_types=['user', 'group']) usemember = f"member_key_id == '{member}' && 'cloudidentity.googleapis.com/groups.discussion_forum' in labels" i += 2 elif myarg == 'delimiter': @@ -501,7 +501,7 @@ def print_members(): ) i += 2 elif myarg == 'enterprisemember': - member = gam.convertUIDtoEmailAddress(sys.argv[i + 1], email_types=['user', 'group']) + member, _ = gam.convertUIDtoEmailAddress(sys.argv[i + 1], email_types=['user', 'group']) usemember = f"member_key_id == '{member}' && 'cloudidentity.googleapis.com/groups.discussion_forum' in labels" i += 2 elif myarg in ['cigroup', 'cigroups']: @@ -876,6 +876,13 @@ def update(): 'cloudidentity.googleapis.com/groups.discussion_forum': '' } i += 1 + elif myarg == 'locked': + body['labels'] = { + 'cloudidentity.googleapis.com/groups.locked': '', + 'cloudidentity.googleapis.com/groups.security': '', + 'cloudidentity.googleapis.com/groups.discussion_forum': '' + } + i += 1 elif myarg == 'dynamicsecurity': body['labels'] = { 'cloudidentity.googleapis.com/groups.dynamic': '', diff --git a/src/gam/gapi/directory/roleassignments.py b/src/gam/gapi/directory/roleassignments.py index 8648389a..4131c5a3 100644 --- a/src/gam/gapi/directory/roleassignments.py +++ b/src/gam/gapi/directory/roleassignments.py @@ -16,7 +16,9 @@ NONSECURITY_GROUP_CONDITION = f'!{SECURITY_GROUP_CONDITION}' def create(): cd = gapi_directory.build() user = gam.normalizeEmailAddressOrUID(sys.argv[3]) - body = {'assignedTo': gam.convertEmailAddressToUID(user, cd)} + body = {'assignedTo': gam.convertEmailAddressToUID(sys.argv[3], + cd=cd, + email_type='any')} role = sys.argv[4] body['roleId'] = gapi_directory_roles.getRoleId(role) body['scopeType'] = sys.argv[5].upper() @@ -70,7 +72,7 @@ def print_(): item_fields = ['roleAssignmentId', 'roleId', 'assignedTo', 'scopeType', 'orgUnitId'] titles = [ 'roleAssignmentId', 'roleId', 'role', 'assignedTo', 'assignedToUser', - 'scopeType', 'orgUnitId', 'orgUnit' + 'assignedToGroup', 'scopeType', 'orgUnitId', 'orgUnit' ] csvRows = [] i = 3 @@ -107,7 +109,21 @@ def print_(): admin_attrib = {} for key, value in list(admin.items()): if key == 'assignedTo': - admin_attrib['assignedToUser'] = gam.user_from_userid(value) + email_types = admin_attrib.get('assigneeType') + if email_types == 'user': + email_field = 'assignedToUser' + elif email_types == 'group': + email_field = 'assignedToGroup' + else: + email_field = None + assignment_email, assignment_type = gam.convertUIDtoEmailAddress(f'uid:{value}', cd, email_types=['user', 'group']) + if not email_field and assignment_type in ['user', 'group']: + if assignment_type == 'user': + email_field = 'assignedToUser' + else: + email_field = 'assignedToGroup' + if email_field: + admin_attrib[email_field] = assignment_email elif key == 'roleId': admin_attrib['role'] = gapi_directory_roles.role_from_roleid(value) elif key == 'orgUnitId': diff --git a/src/gam/gapi/drive/__init__.py b/src/gam/gapi/drive/__init__.py index eacbaa87..6dafcaaa 100644 --- a/src/gam/gapi/drive/__init__.py +++ b/src/gam/gapi/drive/__init__.py @@ -4,5 +4,5 @@ import gam def build(user=None): if not user: user = gam._get_admin_email() - userEmail = gam.convertUIDtoEmailAddress(user) + userEmail, _ = gam.convertUIDtoEmailAddress(user) return (userEmail, gam.buildGAPIServiceObject('drive3', userEmail)) diff --git a/src/gam/gapi/vault.py b/src/gam/gapi/vault.py index 996f235c..2f2353fb 100644 --- a/src/gam/gapi/vault.py +++ b/src/gam/gapi/vault.py @@ -511,7 +511,7 @@ def getHoldInfo(): account_type = 'group' if results['corpus'] == 'GROUPS' else 'user' for i in range(0, len(results['accounts'])): uid = f'uid:{results["accounts"][i]["accountId"]}' - acct_email = gam.convertUIDtoEmailAddress(uid, cd, [account_type]) + acct_email, _ = gam.convertUIDtoEmailAddress(uid, cd, [account_type]) results['accounts'][i]['email'] = acct_email if 'orgUnit' in results: results['orgUnit']['orgUnitPath'] = gapi_directory_orgunits.info( @@ -792,7 +792,7 @@ def getMatterInfo(): cd = gam.buildGAPIObject('directory') for i in range(0, len(result['matterPermissions'])): uid = f'uid:{result["matterPermissions"][i]["accountId"]}' - user_email = gam.convertUIDtoEmailAddress(uid, cd) + user_email, _ = gam.convertUIDtoEmailAddress(uid, cd) result['matterPermissions'][i]['email'] = user_email display.print_json(result)