Expand adminrole commands

This commit is contained in:
Ross Scroggs
2025-08-04 14:33:36 -07:00
parent 63c0c58bf6
commit ef1018f286
3 changed files with 121 additions and 24 deletions

View File

@@ -1511,15 +1511,22 @@ gam show privileges
<RoleItem> ::= id:<String>|uid:<string>|<String> <RoleItem> ::= id:<String>|uid:<string>|<String>
gam create adminrole <String> [description <String>] gam create adminrole <String> [description <String>]
privileges all|all_ou|<PrivilegesList>|(select <FileSelector>|<CSVFileSelector>) privileges all|all_ou|<PrivilegeList>|(select <FileSelector>|<CSVFileSelector>)|<JSONData>
[csv [todrive <ToDriveAttribute>*] [formatjson [quotechar <Character>]] (addcsvdata <FieldName> <String>)*]
gam update adminrole <RoleItem> [name <String>] [description <String>] gam update adminrole <RoleItem> [name <String>] [description <String>]
[privileges all|all_ou|<PrivilegesList>|(select <FileSelector>|<CSVFileSelector>)] [privileges all|all_ou|<PrivilegeList>|(select <FileSelector>|<CSVFileSelector>)|<JSONData>]
[csv [todrive <ToDriveAttribute>*] [formatjson [quotechar <Character>]] (addcsvdata <FieldName> <String>)*]
gam delete adminrole <RoleItem> gam delete adminrole <RoleItem>
gam info adminrole <RoleItem> [privileges] gam info adminrole <RoleItem> [privileges]
[formatjson]
gam print adminroles|roles [todrive <ToDriveAttribute>*] gam print adminroles|roles [todrive <ToDriveAttribute>*]
[role <RoleItem>] [privileges] [oneitemperrow] [role <RoleItem>] [privileges] [oneitemperrow]
[nosystemroles]
[formatjson [quotechar <Character>]]
gam show adminroles|roles gam show adminroles|roles
[role <RoleItem>] [privileges] [role <RoleItem>] [privileges]
[nosystemroles]
[formatjson]
gam create|add admin <EmailAddress>|<UniqueID> <RoleItem> customer|(org_unit <OrgUnitItem>) gam create|add admin <EmailAddress>|<UniqueID> <RoleItem> customer|(org_unit <OrgUnitItem>)
[condition securitygroup|nonsecuritygroup] [condition securitygroup|nonsecuritygroup]

View File

@@ -1,3 +1,20 @@
7.18.01
Added option `nosystemroles` to `gam print|show adminroles` that causes GAM
to only display non-system roles.
Added option `formatjson` to `gam info|print|show adminroles`; this will be most useful
when the `privileges` option is used.
Updated `gam create|update adminrole` to allow specification of privileges with
JSON data: `privileges <JSONData>`. These two updates make it easier to copy admin roles.
Updated `gam create|update adminrole` to allow output of the created/updated
role data in CSV format; by default, GAM displays `<RoleName>(<RoleID>) created|updated`.
```
csv [todrive <ToDriveAttribute>*] [formatjson [quotechar <Character>]] (addcsvdata <FieldName> <String>)*
```
7.18.00 7.18.00
Added commands to display Business Profile Accounts. Added commands to display Business Profile Accounts.

View File

@@ -25,7 +25,7 @@ https://github.com/GAM-team/GAM/wiki
""" """
__author__ = 'GAM Team <google-apps-manager@googlegroups.com>' __author__ = 'GAM Team <google-apps-manager@googlegroups.com>'
__version__ = '7.18.00' __version__ = '7.18.01'
__license__ = 'Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0)' __license__ = 'Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0)'
#pylint: disable=wrong-import-position #pylint: disable=wrong-import-position
@@ -16621,10 +16621,14 @@ def getRoleId():
invalidChoiceExit(role, GM.Globals[GM.MAP_ROLE_NAME_TO_ID], True) invalidChoiceExit(role, GM.Globals[GM.MAP_ROLE_NAME_TO_ID], True)
return (role, roleId) return (role, roleId)
PRINT_ADMIN_ROLES_FIELDS = ['roleId', 'roleName', 'roleDescription', 'isSuperAdminRole', 'isSystemRole']
# gam create adminrole <String> [description <String>] # gam create adminrole <String> [description <String>]
# privileges all|all_ou|<PrivilegesList>|(select <FileSelector>|<CSVFileSelector>) # privileges all|all_ou|<PrivilegeList>|(select <FileSelector>|<CSVFileSelector>)|<JSONData>
# [csv [todrive <ToDriveAttribute>*] [formatjson [quotechar <Character>]] (addcsvdata <FieldName> <String>)*]
# gam update adminrole <RoleItem> [name <String>] [description <String>] # gam update adminrole <RoleItem> [name <String>] [description <String>]
# [privileges all|all_ou|<PrivilegesList>|(select <FileSelector>|<CSVFileSelector>)] # [privileges all|all_ou|<PrivilegeList>|(select <FileSelector>|<CSVFileSelector>)|<JSONData>]
# [csv [todrive <ToDriveAttribute>*] [formatjson [quotechar <Character>]] (addcsvdata <FieldName> <String>)*]
def doCreateUpdateAdminRoles(): def doCreateUpdateAdminRoles():
def expandChildPrivileges(privilege): def expandChildPrivileges(privilege):
for childPrivilege in privilege.get('childPrivileges', []): for childPrivilege in privilege.get('childPrivileges', []):
@@ -16641,6 +16645,9 @@ def doCreateUpdateAdminRoles():
allPrivileges = {} allPrivileges = {}
ouPrivileges = {} ouPrivileges = {}
childPrivileges = {} childPrivileges = {}
csvPF = None
FJQC = FormatJSONQuoteChar(None)
addCSVData = {}
for privilege in _listPrivileges(cd): for privilege in _listPrivileges(cd):
allPrivileges[privilege['privilegeName']] = privilege['serviceId'] allPrivileges[privilege['privilegeName']] = privilege['serviceId']
if privilege['isOuScopable']: if privilege['isOuScopable']:
@@ -16654,6 +16661,8 @@ def doCreateUpdateAdminRoles():
body['rolePrivileges'] = [{'privilegeName': p, 'serviceId': v} for p, v in allPrivileges.items()] body['rolePrivileges'] = [{'privilegeName': p, 'serviceId': v} for p, v in allPrivileges.items()]
elif privs == 'ALL_OU': elif privs == 'ALL_OU':
body['rolePrivileges'] = [{'privilegeName': p, 'serviceId': v} for p, v in ouPrivileges.items()] body['rolePrivileges'] = [{'privilegeName': p, 'serviceId': v} for p, v in ouPrivileges.items()]
elif privs == 'JSON':
body['rolePrivileges'] = getJSON(['roleId', 'roleName', 'isAdminRole', 'isSystemRole']).get('rolePrivileges', [])
else: else:
if privs == 'SELECT': if privs == 'SELECT':
privsList = [p.upper() for p in getEntityList(Cmd.OB_PRIVILEGE_LIST)] privsList = [p.upper() for p in getEntityList(Cmd.OB_PRIVILEGE_LIST)]
@@ -16675,25 +16684,59 @@ def doCreateUpdateAdminRoles():
else: else:
invalidChoiceExit(p, list(allPrivileges.keys())+list(ouPrivileges.keys())+list(childPrivileges.keys()), True) invalidChoiceExit(p, list(allPrivileges.keys())+list(ouPrivileges.keys())+list(childPrivileges.keys()), True)
elif myarg == 'description': elif myarg == 'description':
body['roleDescription'] = getString(Cmd.OB_STRING) body['roleDescription'] = getString(Cmd.OB_STRING, minLen=0)
elif myarg == 'name': elif myarg == 'name':
body['roleName'] = getString(Cmd.OB_STRING) body['roleName'] = getString(Cmd.OB_STRING)
elif myarg == 'csv':
csvPF = CSVPrintFile(PRINT_ADMIN_ROLES_FIELDS)
FJQC.SetCsvPF(csvPF)
elif csvPF and myarg == 'todrive':
csvPF.GetTodriveParameters()
elif csvPF and myarg == 'addcsvdata':
k = getString(Cmd.OB_STRING)
addCSVData[k] = getString(Cmd.OB_STRING, minLen=0)
else: else:
unknownArgumentExit() FJQC.GetFormatJSONQuoteChar(myarg, True)
if not updateCmd and not body.get('rolePrivileges'): if not updateCmd and not body.get('rolePrivileges'):
missingArgumentExit('privileges') missingArgumentExit('privileges')
if csvPF:
if addCSVData:
csvPF.AddTitles(sorted(addCSVData.keys()))
if not FJQC.formatJSON:
csvPF.AddTitles('rolePrivileges')
else:
csvPF.AddJSONTitles(sorted(addCSVData.keys()))
csvPF.MoveJSONTitlesToEnd(['JSON'])
fieldsList = ','.join(PRINT_ADMIN_ROLES_FIELDS+['rolePrivileges'])
else:
fieldsList = 'roleId,roleName'
try: try:
if not updateCmd: if not updateCmd:
result = callGAPI(cd.roles(), 'insert', result = callGAPI(cd.roles(), 'insert',
throwReasons=[GAPI.BAD_REQUEST, GAPI.CUSTOMER_NOT_FOUND, throwReasons=[GAPI.BAD_REQUEST, GAPI.CUSTOMER_NOT_FOUND,
GAPI.FORBIDDEN, GAPI.PERMISSION_DENIED]+[GAPI.DUPLICATE], GAPI.FORBIDDEN, GAPI.PERMISSION_DENIED]+[GAPI.DUPLICATE],
customer=GC.Values[GC.CUSTOMER_ID], body=body, fields='roleId,roleName') customer=GC.Values[GC.CUSTOMER_ID], body=body, fields=fieldsList)
else: else:
result = callGAPI(cd.roles(), 'patch', result = callGAPI(cd.roles(), 'patch',
throwReasons=[GAPI.BAD_REQUEST, GAPI.CUSTOMER_NOT_FOUND, throwReasons=[GAPI.BAD_REQUEST, GAPI.CUSTOMER_NOT_FOUND,
GAPI.FORBIDDEN, GAPI.PERMISSION_DENIED]+[GAPI.NOT_FOUND, GAPI.FAILED_PRECONDITION, GAPI.CONFLICT], GAPI.FORBIDDEN, GAPI.PERMISSION_DENIED]+[GAPI.NOT_FOUND, GAPI.FAILED_PRECONDITION, GAPI.CONFLICT],
customer=GC.Values[GC.CUSTOMER_ID], roleId=roleId, body=body, fields='roleId,roleName') customer=GC.Values[GC.CUSTOMER_ID], roleId=roleId, body=body, fields=fieldsList)
entityActionPerformed([Ent.ADMIN_ROLE, f"{result['roleName']}({result['roleId']})"]) if not csvPF:
entityActionPerformed([Ent.ADMIN_ROLE, f"{result['roleName']}({result['roleId']})"])
else:
if not FJQC.formatJSON:
if addCSVData:
result.update(addCSVData)
csvPF.WriteRowNoFilter(result)
else:
row = {}
for field in PRINT_ADMIN_ROLES_FIELDS:
if field in result:
row[field] = result[field]
if addCSVData:
row.update(addCSVData)
row['JSON'] = json.dumps(cleanJSON(result), ensure_ascii=False, sort_keys=True)
csvPF.WriteRowNoFilter(row)
except GAPI.duplicate as e: except GAPI.duplicate as e:
entityActionFailedWarning([Ent.ADMIN_ROLE, f"{body['roleName']}"], str(e)) entityActionFailedWarning([Ent.ADMIN_ROLE, f"{body['roleName']}"], str(e))
except (GAPI.notFound, GAPI.failedPrecondition, GAPI.conflict) as e: except (GAPI.notFound, GAPI.failedPrecondition, GAPI.conflict) as e:
@@ -16702,6 +16745,8 @@ def doCreateUpdateAdminRoles():
accessErrorExit(cd) accessErrorExit(cd)
except (GAPI.forbidden, GAPI.permissionDenied) as e: except (GAPI.forbidden, GAPI.permissionDenied) as e:
ClientAPIAccessDeniedExit(str(e)) ClientAPIAccessDeniedExit(str(e))
if csvPF:
csvPF.writeCSVfile('Admin Roles')
# gam delete adminrole <RoleItem> # gam delete adminrole <RoleItem>
def doDeleteAdminRole(): def doDeleteAdminRole():
@@ -16721,9 +16766,10 @@ def doDeleteAdminRole():
except (GAPI.forbidden, GAPI.permissionDenied) as e: except (GAPI.forbidden, GAPI.permissionDenied) as e:
ClientAPIAccessDeniedExit(str(e)) ClientAPIAccessDeniedExit(str(e))
PRINT_ADMIN_ROLES_FIELDS = ['roleId', 'roleName', 'roleDescription', 'isSuperAdminRole', 'isSystemRole'] def _showAdminRole(role, FJQC, i=0, count=0):
if FJQC.formatJSON:
def _showAdminRole(role, i=0, count=0): printLine(json.dumps(cleanJSON(role), ensure_ascii=False, sort_keys=True))
return
printEntity([Ent.ADMIN_ROLE, role['roleName']], i, count) printEntity([Ent.ADMIN_ROLE, role['roleName']], i, count)
Ind.Increment() Ind.Increment()
for field in PRINT_ADMIN_ROLES_FIELDS: for field in PRINT_ADMIN_ROLES_FIELDS:
@@ -16744,15 +16790,21 @@ def _showAdminRole(role, i=0, count=0):
Ind.Decrement() Ind.Decrement()
# gam info adminrole <RoleItem> [privileges] # gam info adminrole <RoleItem> [privileges]
# [formatjson]
# gam print adminroles|roles [todrive <ToDriveAttribute>*] # gam print adminroles|roles [todrive <ToDriveAttribute>*]
# [role <RoleItem>] [privileges] [oneitemperrow] # [role <RoleItem>] [privileges] [oneitemperrow]
# [nosystemroles]
# [formatjson [quotechar <Character>]]
# gam show adminroles|roles # gam show adminroles|roles
# [role <RoleItem>] [privileges] # [role <RoleItem>] [privileges]
# [nosystemroles]
# [formatjson]
def doInfoPrintShowAdminRoles(): def doInfoPrintShowAdminRoles():
cd = buildGAPIObject(API.DIRECTORY) cd = buildGAPIObject(API.DIRECTORY)
fieldsList = PRINT_ADMIN_ROLES_FIELDS[:] fieldsList = PRINT_ADMIN_ROLES_FIELDS[:]
csvPF = CSVPrintFile(fieldsList, PRINT_ADMIN_ROLES_FIELDS) if Act.csvFormat() else None csvPF = CSVPrintFile(fieldsList, PRINT_ADMIN_ROLES_FIELDS) if Act.csvFormat() else None
oneItemPerRow = False FJQC = FormatJSONQuoteChar(csvPF)
noSystemRoles = oneItemPerRow = False
if Act.Get() != Act.INFO: if Act.Get() != Act.INFO:
roleId = None roleId = None
else: else:
@@ -16767,13 +16819,17 @@ def doInfoPrintShowAdminRoles():
fieldsList.append('rolePrivileges') fieldsList.append('rolePrivileges')
elif myarg == 'oneitemperrow': elif myarg == 'oneitemperrow':
oneItemPerRow = True oneItemPerRow = True
elif myarg == 'nosystemroles':
noSystemRoles = True
else: else:
unknownArgumentExit() FJQC.GetFormatJSONQuoteChar(myarg, True)
if csvPF and 'rolePrivileges' in fieldsList: if csvPF:
if not oneItemPerRow: if 'rolePrivileges' in fieldsList:
csvPF.AddTitles(['rolePrivileges']) if not oneItemPerRow:
else: if not FJQC.formatJSON:
csvPF.AddTitles(['privilegeName', 'serviceId']) csvPF.AddTitles(['rolePrivileges'])
else:
csvPF.AddTitles(['privilegeName', 'serviceId'])
try: try:
if roleId is None: if roleId is None:
fields = getItemFieldsFromFieldsList('items', fieldsList) fields = getItemFieldsFromFieldsList('items', fieldsList)
@@ -16783,6 +16839,8 @@ def doInfoPrintShowAdminRoles():
throwReasons=[GAPI.BAD_REQUEST, GAPI.CUSTOMER_NOT_FOUND, throwReasons=[GAPI.BAD_REQUEST, GAPI.CUSTOMER_NOT_FOUND,
GAPI.FORBIDDEN, GAPI.PERMISSION_DENIED], GAPI.FORBIDDEN, GAPI.PERMISSION_DENIED],
customer=GC.Values[GC.CUSTOMER_ID], fields=fields) customer=GC.Values[GC.CUSTOMER_ID], fields=fields)
if noSystemRoles:
roles = [role for role in roles if not role.get('isSystemRole', False)]
else: else:
fields = getFieldsFromFieldsList(fieldsList) fields = getFieldsFromFieldsList(fieldsList)
roles = [callGAPI(cd.roles(), 'get', roles = [callGAPI(cd.roles(), 'get',
@@ -16801,23 +16859,38 @@ def doInfoPrintShowAdminRoles():
role.setdefault('isSystemRole', False) role.setdefault('isSystemRole', False)
if not csvPF: if not csvPF:
count = len(roles) count = len(roles)
performActionNumItems(count, Ent.ADMIN_ROLE) if not FJQC.formatJSON:
performActionNumItems(count, Ent.ADMIN_ROLE)
Ind.Increment() Ind.Increment()
i = 0 i = 0
for role in roles: for role in roles:
i += 1 i += 1
_showAdminRole(role, i, count) _showAdminRole(role, FJQC, i, count)
Ind.Decrement() Ind.Decrement()
else: else:
for role in roles: for role in roles:
if not oneItemPerRow or 'rolePrivileges' not in role: if not oneItemPerRow or 'rolePrivileges' not in role:
csvPF.WriteRowTitles(flattenJSON(role)) row = flattenJSON(role)
if not FJQC.formatJSON:
csvPF.WriteRowTitles(row)
elif csvPF.CheckRowTitles(row):
row = {}
for field in PRINT_ADMIN_ROLES_FIELDS:
if field in role:
row[field] = role[field]
row['JSON'] = json.dumps(cleanJSON(role), ensure_ascii=False, sort_keys=True)
csvPF.WriteRowNoFilter(row)
else: else:
privileges = role.pop('rolePrivileges') privileges = role.pop('rolePrivileges')
baserow = flattenJSON(role) baserow = flattenJSON(role)
for privilege in privileges: for privilege in privileges:
row = flattenJSON(privilege, flattened=baserow.copy()) row = flattenJSON(privilege, flattened=baserow.copy())
csvPF.WriteRowTitles(row) if not FJQC.formatJSON:
csvPF.WriteRowTitles(row)
elif csvPF.CheckRowTitles(row):
row = baserow.copy()
row['JSON'] = json.dumps(cleanJSON(privilege), ensure_ascii=False, sort_keys=True)
csvPF.WriteRowNoFilter(row)
if csvPF: if csvPF:
csvPF.writeCSVfile('Admin Roles') csvPF.writeCSVfile('Admin Roles')