def delete(): cd = gapi_directory.build() resourceId = sys.argv[3] gapi.call(cd.mobiledevices(), 'delete', resourceId=resourceId, customerId=GC_Values[GC_CUSTOMER_ID])
def delete_policy(): svc = build() customer = _get_customerid() schemas = build_schemas(svc) orgunit = None printer_id = None app_id = None i = 3 body = {'requests': []} while i < len(sys.argv): myarg = sys.argv[i].lower().replace('_', '') if myarg in ['ou', 'org', 'orgunit']: orgunit = _get_orgunit(sys.argv[i+1]) i += 2 elif myarg == 'printerid': printer_id = sys.argv[i+1] i += 2 elif myarg == 'appid': app_id = sys.argv[i+1] i += 2 elif myarg in schemas: body['requests'].append({'policySchema': schemas[myarg]['name']}) i += 1 else: msg = f'{myarg} is not a valid argument to "gam delete chromepolicy"' controlflow.system_error_exit(3, msg) if not orgunit: controlflow.system_error_exit(3, 'You must specify an orgunit') for request in body['requests']: request['policyTargetKey'] = {'targetResource': orgunit} if printer_id: request['policyTargetKey']['additionalTargetKeys'] = {'printer_id': printer_id} elif app_id: request['policyTargetKey']['additionalTargetKeys'] = {'app_id': app_id} gapi.call(svc.customers().policies().orgunits(), 'batchInherit', customer=customer, body=body)
def addACL(function): calendarId, cal = buildCalendarDataGAPIObject(sys.argv[2]) if not cal: return myarg = sys.argv[4].lower().replace('_', '') if myarg not in CALENDAR_ACL_ROLES_MAP: controlflow.expected_argument_exit('Role', ', '.join(CALENDAR_ACL_ROLES_MAP), myarg) body = {'role': CALENDAR_ACL_ROLES_MAP[myarg]} i = _getCalendarACLScope(5, body) sendNotifications = True while i < len(sys.argv): myarg = sys.argv[i].lower().replace('_', '') if myarg == 'sendnotifications': sendNotifications = gam.getBoolean(sys.argv[i + 1], myarg) i += 2 else: controlflow.invalid_argument_exit( sys.argv[i], f'gam calendar <email> {function.lower()}') print(f'Calendar: {calendarId}, {function} ACL: {formatACLRule(body)}') gapi.call(cal.acl(), 'insert', calendarId=calendarId, body=body, sendNotifications=sendNotifications)
def update(users, sku=None, old_sku=None): lic = build() if not sku: sku = sys.argv[5] productId, skuId = getProductAndSKU(sku) sku_name = _formatSKUIdDisplayName(skuId) i = 6 if len(sys.argv) > 6 and sys.argv[i].lower() in ['product', 'productid']: productId = sys.argv[i + 1] i += 2 if not old_sku: try: old_sku = sys.argv[i] if old_sku.lower() == 'from': old_sku = sys.argv[i + 1] except KeyError: controlflow.system_error_exit( 2, 'You need to specify the user\'s old SKU as the last argument') _, old_sku = getProductAndSKU(old_sku) old_sku_name = _formatSKUIdDisplayName(old_sku) for user in users: print( f'Changing user {user} from license {old_sku_name} to {sku_name}') gapi.call(lic.licenseAssignments(), 'patch', soft_errors=True, productId=productId, skuId=old_sku, userId=user, body={'skuId': skuId})
def update(): cd = gapi_directory.build() body = {} roleId = gam.getRoleId(sys.argv[3]) i = 4 while i < len(sys.argv): myarg = sys.argv[i].lower() if myarg == 'privileges': getPrivileges(body, sys.argv[i + 1].upper(), 'update') i += 2 elif myarg == 'description': body['roleDescription'] = sys.argv[i + 1] i += 2 elif myarg == 'name': body['roleName'] = sys.argv[i + 1] i += 2 else: controlflow.invalid_argument_exit(sys.argv[i], 'gam update adminrole') print(f'Updating role {roleId}') gapi.call(cd.roles(), 'patch', customer=GC_Values[GC_CUSTOMER_ID], roleId=roleId, body=body)
def doUpdateCustomer(): cd = gapi_directory.build() body = {} customer_id = _get_customerid() i = 3 while i < len(sys.argv): myarg = sys.argv[i].lower().replace('_', '') if myarg in ADDRESS_FIELDS_ARGUMENT_MAP: body.setdefault('postalAddress', {}) arg = ADDRESS_FIELDS_ARGUMENT_MAP[myarg] body['postalAddress'][arg] = sys.argv[i + 1] i += 2 elif myarg in ['adminsecondaryemail', 'alternateemail']: body['alternateEmail'] = sys.argv[i + 1] i += 2 elif myarg in ['phone', 'phonenumber']: body['phoneNumber'] = sys.argv[i + 1] i += 2 elif myarg == 'language': body['language'] = sys.argv[i + 1] i += 2 else: controlflow.invalid_argument_exit(myarg, 'gam update customer') if not body: controlflow.system_error_exit( 2, 'no arguments specified for "gam ' 'update customer"') gapi.call(cd.customers(), 'patch', customerKey=customer_id, body=body) print('Updated customer')
def test_call_retries_requests_for_provided_retry_reasons( self, unused_mock_wait_on_failure): retry_reason1 = errors.ErrorReason.INTERNAL_ERROR fake_retrieable_error1 = create_http_error(400, retry_reason1, 'Forced Error 1') retry_reason2 = errors.ErrorReason.SYSTEM_ERROR fake_retrieable_error2 = create_http_error(400, retry_reason2, 'Forced Error 2') non_retriable_reason = errors.ErrorReason.SERVICE_NOT_AVAILABLE fake_non_retriable_error = create_http_error( 400, non_retriable_reason, 'This error should not cause the request to be retried') # Fail once, then succeed on retry self.mock_method.return_value.execute.side_effect = [ fake_retrieable_error1, fake_retrieable_error2, fake_non_retriable_error ] with self.assertRaises(SystemExit): # The third call should raise the SystemExit when non_retriable_error is # raised. gapi.call(self.mock_service, self.mock_method_name, retry_reasons=[retry_reason1, retry_reason2]) self.assertEqual(self.mock_method.return_value.execute.call_count, 3)
def update(): cbcm = build() device_id = sys.argv[3] body = {'deviceId': device_id} i = 4 while i < len(sys.argv): myarg = sys.argv[i].lower().replace('_', '') if myarg in attributes: body[attributes[myarg]] = sys.argv[i + 1] i += 2 else: controlflow.invalid_argument_exit(sys.argv[i], 'gam update browser') browser = gapi.call(cbcm.chromebrowsers(), 'get', deviceId=device_id, customer=GC_Values[GC_CUSTOMER_ID], projection='BASIC', fields=attribute_fields) browser.update(body) result = gapi.call(cbcm.chromebrowsers(), 'update', deviceId=device_id, customer=GC_Values[GC_CUSTOMER_ID], body=browser, projection='BASIC', fields="deviceId") print(f'Updated browser {result["deviceId"]}')
def createMatter(): v = buildGAPIObject() matter_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') body = {'name': f'New Matter - {matter_time}'} collaborators = [] cd = None i = 3 while i < len(sys.argv): myarg = sys.argv[i].lower().replace('_', '') if myarg == 'name': body['name'] = sys.argv[i + 1] i += 2 elif myarg == 'description': body['description'] = sys.argv[i + 1] i += 2 elif myarg in ['collaborator', 'collaborators']: if not cd: cd = gam.buildGAPIObject('directory') collaborators.extend(validateCollaborators(sys.argv[i + 1], cd)) i += 2 else: controlflow.invalid_argument_exit(sys.argv[i], 'gam create matter') matterId = gapi.call(v.matters(), 'create', body=body, fields='matterId')['matterId'] print(f'Created matter {matterId}') for collaborator in collaborators: print(f' adding collaborator {collaborator["email"]}') body = { 'matterPermission': { 'role': 'COLLABORATOR', 'accountId': collaborator['id'] } } gapi.call(v.matters(), 'addPermissions', matterId=matterId, body=body)
def getOrgUnitId(orgUnit, cd=None): if cd is None: cd = gapi_directory.build() orgUnit = getOrgUnitItem(orgUnit) if orgUnit[:3] == 'id:': return (orgUnit, orgUnit) if orgUnit == '/': result = gapi.call(cd.orgunits(), 'list', customerId=GC_Values[GC_CUSTOMER_ID], orgUnitPath='/', type='children', fields='organizationUnits(parentOrgUnitId)') if result.get('organizationUnits', []): return (orgUnit, result['organizationUnits'][0]['parentOrgUnitId']) topLevelOrgId = getTopLevelOrgId(cd, '/') if topLevelOrgId: return (orgUnit, topLevelOrgId) return (orgUnit, '/') #Bogus but should never happen result = gapi.call(cd.orgunits(), 'get', customerId=GC_Values[GC_CUSTOMER_ID], orgUnitPath=encodeOrgUnitPath( makeOrgUnitPathRelative(orgUnit)), fields='orgUnitId') return (orgUnit, result['orgUnitId'])
def createFeature(): cd = gapi_directory.build() body = _getFeatureAttributes(sys.argv[3:]) print(f'Creating feature {body["name"]}...') gapi.call(cd.resources().features(), 'insert', customer=GC_Values[GC_CUSTOMER_ID], body=body)
def delete(): cd = gapi_directory.build() roleAssignmentId = sys.argv[3] print(f'Deleting Admin Role Assignment {roleAssignmentId}') gapi.call(cd.roleAssignments(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], roleAssignmentId=roleAssignmentId)
def test_call_exits_on_nonretriable_error(self): error_reason = 'unknownReason' fake_http_error = create_http_error(500, error_reason, 'Testing unretriable errors') self.mock_method.return_value.execute.side_effect = fake_http_error with self.assertRaises(SystemExit): gapi.call(self.mock_service, self.mock_method_name)
def test_call_exits_on_oauth_token_error(self): # An error with any OAUTH2_TOKEN_ERROR fake_token_error = gapi.google.auth.exceptions.RefreshError( errors.OAUTH2_TOKEN_ERRORS[0]) self.mock_method.return_value.execute.side_effect = fake_token_error with self.assertRaises(SystemExit): gapi.call(self.mock_service, self.mock_method_name)
def revoketoken(): cbcm = build() token_permanent_id = sys.argv[3] gapi.call(cbcm.enrollmentTokens(), 'revoke', tokenPermanentId=token_permanent_id, customer=GC_Values[GC_CUSTOMER_ID]) print(f'Deleted browser enrollment token {token_permanent_id}')
def delete(): cbcm = build() device_id = sys.argv[3] gapi.call(cbcm.chromebrowsers(), 'delete', deviceId=device_id, customer=GC_Values[GC_CUSTOMER_ID]) print(f'Deleted browser {device_id}')
def deleteFeature(): cd = gapi_directory.build() featureKey = sys.argv[3] print(f'Deleting feature {featureKey}...') gapi.call(cd.resources().features(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], featureKey=featureKey)
def deleteBuilding(): cd = gapi_directory.build() buildingId = getBuildingByNameOrId(cd, sys.argv[3]) print(f'Deleting building {buildingId}...') gapi.call(cd.resources().buildings(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], buildingId=buildingId)
def delete(): cd = gapi_directory.build() name = getOrgUnitItem(sys.argv[3]) print(f'Deleting organization {name}') gapi.call(cd.orgunits(), 'delete', customerId=GC_Values[GC_CUSTOMER_ID], orgUnitPath=encodeOrgUnitPath(makeOrgUnitPathRelative(name)))
def delete(): cd = gapi_directory.build() domainName = sys.argv[3] print(f'Deleting domain {domainName}') gapi.call(cd.domains(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], domainName=domainName)
def delete(): cd = gapi_directory.build() roleId = gam.getRoleId(sys.argv[3]) print(f'Deleting role {roleId}') gapi.call(cd.roles(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], roleId=roleId)
def deleteResourceCalendar(): resId = sys.argv[3] cd = gapi_directory.build() print(f'Deleting resource calendar {resId}') gapi.call(cd.resources().calendars(), 'delete', customer=GC_Values[GC_CUSTOMER_ID], calendarResourceId=resId)
def transferSecCals(users): target_user = sys.argv[5] remove_source_user = sendNotifications = True i = 6 while i < len(sys.argv): myarg = sys.argv[i].lower().replace('_', '') if myarg == 'keepuser': remove_source_user = False i += 1 elif myarg == 'sendnotifications': sendNotifications = gam.getBoolean(sys.argv[i + 1], myarg) i += 2 else: controlflow.invalid_argument_exit(sys.argv[i], 'gam <users> transfer seccals') if remove_source_user: target_user, target_cal = buildCalendarGAPIObject(target_user) if not target_cal: return for user in users: user, source_cal = buildCalendarGAPIObject(user) if not source_cal: continue calendars = gapi.get_all_pages(source_cal.calendarList(), 'list', 'items', soft_errors=True, minAccessRole='owner', showHidden=True, fields='items(id),nextPageToken') for calendar in calendars: calendarId = calendar['id'] if calendarId.find('@group.calendar.google.com') != -1: body = { 'role': 'owner', 'scope': { 'type': 'user', 'value': target_user } } gapi.call(source_cal.acl(), 'insert', calendarId=calendarId, body=body, sendNotifications=sendNotifications) if remove_source_user: body = { 'role': 'none', 'scope': { 'type': 'user', 'value': user } } gapi.call(target_cal.acl(), 'insert', calendarId=calendarId, body=body, sendNotifications=sendNotifications)
def revoketoken(): cbcm = build() customer_id = _get_customerid() token_permanent_id = sys.argv[3] gapi.call(cbcm.enrollmentTokens(), 'revoke', tokenPermanentId=token_permanent_id, customer=customer_id) print(f'Deleted browser enrollment token {token_permanent_id}')
def deleteExport(): v = buildGAPIObject() matterId = getMatterItem(v, sys.argv[3]) exportId = convertExportNameToID(v, sys.argv[4], matterId) print(f'Deleting export {sys.argv[4]} / {exportId}') gapi.call(v.matters().exports(), 'delete', matterId=matterId, exportId=exportId)
def test_call_passes_target_method_params(self): gapi.call(self.mock_service, self.mock_method_name, my_param_1=1, my_param_2=2) self.assertEqual(self.mock_method.call_count, 1) method_kwargs = self.mock_method.call_args[1] self.assertEqual(method_kwargs.get('my_param_1'), 1) self.assertEqual(method_kwargs.get('my_param_2'), 2)
def signout(users): cd = gapi_directory.build() i = 0 count = len(users) for user in users: i += 1 user = gam.normalizeEmailAddressOrUID(user) print(f'Signing Out {user}{gam.currentCount(i, count)}') gapi.call(cd.users(), 'signOut', soft_errors=True, userKey=user)
def create(): cd = gapi_directory.build() domain_name = sys.argv[3] body = {'domainName': domain_name} gapi.call(cd.domains(), 'insert', customer=GC_Values[GC_CUSTOMER_ID], body=body) print(f'Added domain {domain_name}')
def delete(): cbcm = build() device_id = sys.argv[3] customer_id = _get_customerid() gapi.call(cbcm.chromebrowsers(), 'delete', deviceId=device_id, customer=customer_id) print(f'Deleted browser {device_id}')
def createResourceCalendar(): cd = gapi_directory.build() body = {'resourceId': sys.argv[3], 'resourceName': sys.argv[4]} body = _getResourceCalendarAttributes(cd, sys.argv[5:], body) print(f'Creating resource {body["resourceId"]}...') gapi.call(cd.resources().calendars(), 'insert', customer=GC_Values[GC_CUSTOMER_ID], body=body)