Debian Codegraph @

redfishtoollib/AccountService.py

raw symbols SCIP
1 # Copyright Notice:
2 # Copyright 2016 DMTF. All rights reserved.
3 # License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfishtool/blob/master/LICENSE.md
4
5 # redfishtool: AccountService.py
6 #
7 # contains AccountService related subCommands and access functions
8 #
9 # Class RfAccountServiceMain
10 # - functions init, displayUsage, displayHelp, displayOperations,
11 # - runOperation - AccountService command table, dispatch of operation eg get, reset
12 # - AccountServiceMain - called from redfishMain, enforce legal option combinations,
13 # and call runOperation to run AccountService operation (sub-sub-command)
14 #
15 # Class RfAccountServiceOperations
16 # All of the AccountService sub-command operations eg: get AccountService,Accounts, Sessions, adduser... etc
17 # - hello - test cmd
18 # - get - get the account service
19 # - patch - raw subcommand to patch a accountService, with etag support
20 # - Accounts - get Accounts collection, Accounts instance, list Accounts, get all Accounts
21 # - Roles - get Roles collection, Roles instance, list Roles, get all Roles
22 # - adduser - add a new user to Accounts collection
23 # - setpassword - update the password of an existing user account
24 # - deleteuser - delete an existin user from Accouts collection
25 # - userAdmin - enable, disable, or unlock a user account
26 # - addRole - add a new custom role to the Roles collection
27 # - deleteRole - delete an existing role from Roles collection
28 # - examples --prints some example apis
29 #
30 from .redfishtoolTransport import RfTransport
31 import requests
32 import json
33 import getopt
34 import re
35 import sys
36 from .ServiceRoot import RfServiceRoot
37 from urllib.parse import urljoin
38
39 class RfAccountServiceMain():
40 def __init__(self):
41 # operation string and remaining args
42 self.operation=None
43 self.args=None
44 self.argnum=0
45 self.nonIdCommands=None
46
47 def displayUsage(self,rft):
48 if(rft.quiet): return(0)
49 print(" Usage:")
50 print(" {} [OPTNS] AccountService <operation> [<args>] -- perform <operation> on the AccountService ".format(rft.program))
51
52 def displayHelp(self,rft):
53 self.displayUsage(rft)
54 self.displayOperations(rft)
55 print("")
56
57 def displayOperations(self,rft):
58 print(" <operations>:")
59 print(" [get] -- get the AccountService object. ")
60 print(" patch {A: B,C: D,...} -- patch the AccountService w/ json-formatted {prop: value...} ")
61 print(" Accounts [list] -- get the \"Accounts\" collection, or list \"Id\", username, and Url ")
62 print(" Accounts [IDOPTN] -- get the member specified by IDOPTN: -i<Id>, -m<prop>:<val>, -l<link>, -a #all")
63 print(" Roles [list] -- get the \"Roles\" collection, or list \"Id\", IsPredefined, and Url ")
64 print(" Roles [IDOPTN] -- get the member specified by IDOPTN: -i<Id>, -m<prop>:<val>, -l<link>, -a #all")
65 print(" adduser <usernm> <passwd> [<roleId>] -- add a new user to the Accounts collection")
66 print(" -- <roleId>:{Administrator | Operator | ReadOnlyUser | <a custom roleId}, dflt=Operator")
67 print(" deleteuser <usernm> -- delete an existing user from Accouts collection")
68 print(" setpassword <usernm> <passwd> -- set (change) the password of an existing user account")
69 print(" useradmin <userName> [enable|disable|unlock|[setRoleId <roleId>]] -- enable|disable|unlock.. a user account")
70 print(" setusername <id> <userName> -- set UserName for account with given Id")
71 #print(" addrole <roleId> <listOfPrivileges> -- add a new custom role to the Roles collection")
72 #print(" -- <listOfPrivileges> is string of form: Login,ConfigeUsers,ConfigureSelf...")
73 #print(" deleterole <roleId> -- delete an existing role from Roles collection")
74 print(" examples -- example commands with syntax")
75 print(" hello -- AccountService hello -- debug command")
76 return(0)
77
78 # - changePassword - update the password of an existing user account
79 # - deleteUser - delete an existin user from Accouts collection
80 # - userAdmin - enable, disable, or unlock a user account
81 # - addRole - add a new custom role to the Roles collection
82 # - deleteRole - delete an existing role from Roles collection
83 # - examples --prints some example apis
84
85 def runOperation(self,rft):
86 # instantiate AccountService class
87 op=RfAccountServiceOperations()
88
89 # dispatch table for each subcommand: "cmdName": cmdClass.cmdFunction"
90 operationTable = {
91 "get": op.get,
92 "patch": op.patch,
93 "Accounts": op.getAccounts,
94 "Roles": op.getRoles,
95 "adduser": op.addUser,
96 "deleteuser": op.deleteUser,
97 "setpassword": op.setPassword,
98 "useradmin": op.userAdmin,
99 "setusername": op.setUsername,
100 #"addrole": op.addRole,
101 #"deleterole": op.deleteRole,
102 "hello": op.hello,
103 "examples": op.examples
104 }
105
106 rft.printVerbose(5,"AccountService:runOperation: operation: {}".format(self.operation))
107 rft.printVerbose(5,"AccountService:runOperation: args: {}".format(self.args))
108
109 if self.operation in operationTable:
110 rft.printVerbose(5,"AccountService:runOperation: found Oper: {} in table. executing".format(rft.subcommand))
111 rc,r,j,d=operationTable[self.operation](self, op, rft, cmdTop=True)
112 return(rc,r,j,d)
113
114 else: # invalid operation
115 rft.printErr("AccountService: Invalid operation: {}".format(self.operation))
116 return(2,None,False,None)
117
118
119
120 def AccountServiceMain(self,rft,cmdTop=False):
121 rft.printVerbose(4,"AccountServiceMain: subcommand: {}".format(rft.subcommand))
122
123 if( rft.help ):
124 self.displayHelp(rft)
125 return(0,None,False,None)
126
127 # we will validate usage of -P and -a in action processing
128 # actually, if a non 'get' action is specified, -P and -a are just ignored :)
129
130 args=rft.subcommandArgv[0:]
131
132 #if no args, this is a getAccountService command
133 if( len(args) < 2 ):
134 self.operation="get"
135 self.args= None
136 else:
137 self.operation=args[1]
138 self.args = args[1:] # now args points to the 1st argument
139 self.argnum =len(self.args)
140
141 rft.printVerbose(5,"AccountService: operation={}, args={}".format(self.operation,self.args))
142
143 # now execute the operation.
144 rc,r,j,d = self.runOperation(rft)
145
146 if(rc !=0 ):
147 rft.printVerbose(5,"AccountService: operation returned with error: rc={}".format(rc))
148 return(rc,r,False,None)
149
150 #else, if here, the subcommand executed without error. Return with 0 exit code
151 rft.printVerbose(5,"AccountService: operation exited OK")
152 return(rc,r,j,d)
153
154
155 #
156 # contains operations related to the AccountService subCommand
157 #
158 class RfAccountServiceOperations():
159 def __init__(self):
160 self.AccountServicePath=None
161 self.AccountServiceCollectionDict=None
162
163
164 def hello(self,sc,op,rft,cmdTop=False):
165 rft.printVerbose(4,"in hello")
166 rft.printVerbose(4," subcmd:{}, operation:{}, args:{}".format(rft.subcommand,sc.operation,sc.args))
167 print("hello world from AccountService")
168 return(0,None,False,None)
169
170
171
172 def get(self,sc,op,rft, cmdTop=False, prop=None):
173 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
174
175 # 1st get serviceRoot
176 svcRoot=RfServiceRoot()
177 rc,r,j,d = svcRoot.getServiceRoot(rft)
178 if( rc != 0 ):
179 rft.printErr("get AccountService: Error getting service root, aborting")
180 return(rc,r,False,None)
181
182 # get the link to the AccountService
183 # need to test we got good data
184 if (("AccountService" in d) and ("@odata.id" in d["AccountService"])):
185 accountServiceLink=d["AccountService"]["@odata.id"]
186 else:
187 rft.printErr("Error: root does not have a AccountService link")
188 return(4)
189
190 rft.printVerbose(4,"AccountService: get AccountService: link is: {}".format(accountServiceLink))
191
192 if cmdTop is True: prop=rft.prop
193
194 # do a GET to get the AccountService, if -P show property, else show full response
195 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=accountServiceLink, prop=prop)
196
197 if(rc==0): rft.printVerbose(1," AccountService Resource:",skip1=True, printV12=cmdTop)
198 return(rc,r,j,d)
199
200
201
202 def patch(self,sc,op,rft,cmdTop=False, prop=None, patchData=None, r=None):
203 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
204 # verify we have got an argument which is the patch structure
205 # its in form '{ "AssetTag": <val>, "IndicatorLed": <val> }'
206 ##print("patchData: {}".format(patchData))
207 if( len( sc.args) == 2):
208 ##print("data:{}".format(sc.args[1]))
209 try:
210 patchData=json.loads(sc.args[1])
211 except ValueError:
212 rft.printErr("Patch: invalid Json input data:{}".format(sc.args[1]))
213 return(5,None,False,None)
214 ##print("patchData: {}".format(patchData))
215 else:
216 rft.printErr("Patch: error: invalid argument format")
217 rft.printErr(" : args={}".format(sc.args))
218 rft.printErr(" : expect: SessionService patch \"{ <prop>: <value> }\"")
219 return(4,None,False,None)
220
221 # read the AccountService resource
222 # this is used by the generic rft.patchResource() function to see if there is an etag in the response
223 # if an etag is in response hdr, then we must include the etag on the patch, so this get is required
224 # note: the format of etag header for redfish is: ETag: W/"<string>" or "<string"
225 rc,r,j,d=op.get(sc,op,rft)
226 if( rc != 0):
227 return(rc,r,False,None)
228
229 # now call the generic patch function to send the patch
230 rc,r,j,d=rft.patchResource(rft, r, patchData)
231
232 if(rc==0): rft.printVerbose(1," AccountService Patch:",skip1=True, printV12=cmdTop)
233 return(rc,r,j,d)
234
235
236
237
238 def getAccounts(self,sc,op, rft, cmdTop=False, prop=None):
239 rft.printVerbose(4,"{}:{}: in operation: getAccounts collection".format(rft.subcommand,sc.operation))
240
241 # get the AccountService resource
242 rc,r,j,d=op.get(sc,op, rft)
243 if( rc != 0): return(rc,r,False,None)
244
245 collName="Accounts"
246 # get the link to the Accounts collection
247 if ((collName in d) and ("@odata.id" in d[collName])):
248 accountsLink=d[collName]["@odata.id"]
249 else:
250 rft.printErr("Error: AccountsService resource does not have a {} link".format(collName))
251 return(6,None,False,None)
252
253 if cmdTop is True: prop=rft.prop
254
255 # check if there is a list arg for the operation
256 if( sc.argnum > 1 and sc.args[1] == 'list' ):
257 #get the collection
258 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=accountsLink)
259 #loop through the members and create the list sub-operation response
260 rc,r,j,d=rft.listCollection(rft, r, d, prop="UserName")
261 if(rc==0):
262 rft.printVerbose(1," list {} Collection member info: Id, URI, UserName".format(collName,skip1=True, printV12=cmdTop))
263
264 # else: check if no account was specified. If not, return the collection
265 elif(rft.IdLevel2OptnCount==0):
266 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=accountsLink, prop=prop)
267 if(rc==0):
268 rft.printVerbose(1," {} Collection ".format(collName,skip1=True, printV12=cmdTop))
269
270 # else: check if the -a (all) option is set. If not, return the session specific by -i or -m or -l
271 # search collection to find path using getPath2
272 elif( rft.allOptn is not True ):
273 # get the Accounts collection
274 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=accountsLink, prop=prop)
275 collUrl=r.url
276
277 # now search for 2nd level resource and return
278 path2,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d)
279 if(rc!=0):
280 return(rc,r,j,d)
281 # so rc=0
282 #if sysPath returned a response but we need to extract the property do it here
283 if( (r is not None) and (prop is not None) ):
284 rc,r,j,d=rft.getPropFromDict(rft,r,d,prop)
285
286 # otherwise, we need to do a GET to get the account, if -P show property, else show full response
287 elif( r is None ):
288 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', collUrl, relPath=path2, prop=prop)
289 if(rc==0):
290 rft.printVerbose(1," {} Collection Member ".format(collName,skip1=True, printV12=cmdTop))
291
292 # else, return ALL of the Accounts members
293 else:
294 rft.printVerbose(4,"getting expanded Accounts Collection")
295 rc,r,j,d=rft.getAllCollectionMembers(rft, r.url, relPath=accountsLink)
296 if(rc==0):
297 rft.printVerbose(1," Get ALL {} Collection Members".format(collName,skip1=True, printV12=cmdTop))
298
299 return(rc,r,j,d)
300
301
302
303 def getRoles(self,sc,op, rft, cmdTop=False, prop=None):
304 rft.printVerbose(4,"{}:{}: in operation: getRoles collection".format(rft.subcommand,sc.operation))
305
306 # get the AccountService resource
307 rc,r,j,d=op.get(sc,op, rft)
308 if( rc != 0): return(rc,r,False,None)
309
310 collName="Roles"
311 # get the link to the Roles collection
312 if ((collName in d) and ("@odata.id" in d[collName])):
313 rolesLink=d[collName]["@odata.id"]
314 else:
315 rft.printErr("Error: AccountsService resource does not have a {} link".format(collName))
316 return(6,None,False,None)
317
318 if cmdTop is True: prop=rft.prop
319
320 # check if there is a list arg for the operation
321 if( sc.argnum > 1 and sc.args[1] == 'list' ):
322 #get the collection
323 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=rolesLink)
324 #loop through the members and create the list sub-operation response
325 rc,r,j,d=rft.listCollection(rft, r, d, prop="IsPredefined")
326 if(rc==0):
327 rft.printVerbose(1," list {} Collection member info: Id, URI, IsPredefined".format(collName,skip1=True, printV12=cmdTop))
328
329 # else: check if no account was specified. If not, return the collection
330 elif(rft.IdLevel2OptnCount==0):
331 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=rolesLink, prop=prop)
332 if(rc==0):
333 rft.printVerbose(1," {} Collection ".format(collName,skip1=True, printV12=cmdTop))
334
335 # else: check if the -a (all) option is set. If not, return the session specific by -i or -m or -l
336 # search collection to find path using getPath2
337 elif( rft.allOptn is not True ):
338 # get the Accounts collection
339 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=rolesLink, prop=prop)
340 collUrl=r.url
341
342 # now search for 2nd level resource and return
343 path2,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d)
344 if(rc!=0):
345 return(rc,r,j,d)
346 # so rc=0
347 #if sysPath returned a response but we need to extract the property do it here
348 if( (r is not None) and (prop is not None) ):
349 rc,r,j,d=rft.getPropFromDict(rft,r,d,prop)
350
351 # otherwise, we need to do a GET to get the account, if -P show property, else show full response
352 elif( r is None ):
353 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', collUrl, relPath=path2, prop=prop)
354 if(rc==0):
355 rft.printVerbose(1," {} Collection Member ".format(collName,skip1=True, printV12=cmdTop))
356
357 # else, return ALL of the Accounts members
358 else:
359 rft.printVerbose(4,"getting expanded Roles Collection")
360 rc,r,j,d=rft.getAllCollectionMembers(rft, r.url, relPath=rolesLink)
361 if(rc==0):
362 rft.printVerbose(1," Get ALL {} Collection Members".format(collName,skip1=True, printV12=cmdTop))
363
364 return(rc,r,j,d)
365
366
367
368
369 # adduser <username> <passwd> [<roleId>] ---add a new user
370 def addUser(self,sc,op,rft,cmdTop=False, prop=None):
371 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
372
373 # verify we got 2 args <username> and <passwd>
374 # if we got 3rd arg <roleId>, use it, otherwise use builtin Operator role
375 # get the Accounts collection
376 # then verify we don't already have a user with that username
377 # then get Roles collection, and verify it is a valid role for that system
378 # create patch string
379 # POST new entry to Accounts with: user, passwd, roleId to create new user
380
381 # verify we have two addl arg,
382 if(len(sc.args) < 3 ):
383 rft.printErr("Error, adduser: invalid number of arguments")
384 rft.printErr("Syntax: {} AccountService adduser <username> <passwd> [<roleId>]".format(rft.program))
385 rft.printErr(" default <roleId> is Operator")
386 return(8,None,False,None)
387
388 # get the <username> and <password> from args
389 userName=sc.args[1]
390 password=sc.args[2]
391
392 # if a roleId was specified (arg3), then use it, otherwise use default operator
393 if(len(sc.args) > 3 ):
394 roleVal=sc.args[3]
395 else:
396 roleVal="Operator"
397
398 # get Accounts collection
399 rc,r,j,d=op.getAccounts(sc,op, rft)
400 if( rc != 0): return(rc,r,False,None)
401 accountsUrl=r.url
402
403 # check if we already have a user with this username
404 rft.gotMatchLevel2Optn=True
405 rft.matchLevel2Prop="UserName"
406 rft.matchLevel2Value=userName
407 path,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d) # this will return path to the acct as well as current resource in d
408 if( rc == 0): # if we found the user with this name
409 rft.printErr("Error: username {} already exists".format(userName))
410 return(9,None,False,None)
411
412 # verify that the specified RoleId is valid for this system
413 # get Roles collection
414 rc,r,j,d=op.getRoles(sc,op, rft)
415 if( rc != 0): return(rc,r,False,None)
416 # check if the roleId specified is supported on this platform
417 rft.gotMatchLevel2Optn=True
418 rft.matchLevel2Prop="Id"
419 rft.matchLevel2Value=roleVal
420 path,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d) # this will return path to the acct as well as current resource in d
421 if( rc != 0):
422 rft.printErr("Error: roleId: {} is not supported on remote service".format(roleVal))
423 return(rc,None,False,None)
424
425 # create POST request data
426 postData={"UserName": userName, "Password": password, "RoleId": roleVal}
427
428 # POST new entry to Accounts with: user, passwd, roleId to create new user
429 reqPostData=json.dumps(postData)
430 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'POST', accountsUrl, reqData=reqPostData)
431 if(rc==0):
432 rft.printVerbose(1," Add User: {} (POST to Accounts collection): ".format(userName), skip1=True, printV12=cmdTop)
433 respData=d
434 return(rc,r,j,respData)
435 else: return(rc,r,False,None)
436
437
438
439
440 # deleteuser <username>
441 def deleteUser(self,sc,op,rft,cmdTop=False, prop=None):
442 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
443
444 # verify one addl arg username
445 # get Accounts collection
446 # then find the Account entry for username, and verify we have that user
447 # sent DELETE to Accounts collection to remove the account
448
449 # verify we have one addl arg: username
450 if(len(sc.args) < 2 ):
451 rft.printErr("Error, deleteuser: invalid number of arguments")
452 rft.printErr("Syntax: {} AccountService deleteuser <username>".format(rft.program))
453 return(8,None,False,None)
454
455 # get the <username> and <password> from args
456 userName=sc.args[1]
457
458 # get Accounts collection
459 rc,r,j,d=op.getAccounts(sc,op, rft)
460 if( rc != 0): return(rc,r,False,None)
461 accountsUrl=r.url
462
463 # check if we indeed have a user with this username
464 rft.gotMatchLevel2Optn=True
465 rft.matchLevel2Prop="UserName"
466 rft.matchLevel2Value=userName
467 accountPath,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d) # this will return path to the acct as well as current resource in d
468 if( rc != 0): # if we found the user with this name
469 rft.printErr("Error: username {} does not exists".format(userName))
470 return(9,None,False,None)
471
472 # send DELETE to this account Url to remove it from the Accounts collection
473 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'DELETE', accountsUrl, relPath=accountPath)
474 if(rc==0):
475 rft.printVerbose(1," Delete User: {} (DELETE to Account entry): ".format(userName), skip1=True, printV12=cmdTop)
476 return(rc,r,False,None)
477 else: return(rc,r,False,None)
478
479
480
481
482 # useradmin <username> {enable|disable|unlock|{setRoleId <roleId>}}
483 def userAdmin(self,sc,op,rft,cmdTop=False, prop=None):
484 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
485
486 # verify we have two addl arg, and it is a valid keyword: enable,disable,unlock,setRoleId=...
487 # create the patch strint
488 # get Accounts collection
489 # then find the Accounts entry for username, and verify we have that user
490 # verify the service supports the properties we need to set
491 # send patch to set the properties
492 #print("arglen:{}, arg0:{}, args:{}".format(len(sc.args),sc.args[0], sc.args))
493
494 # verify we have two addl arg,
495 if(len(sc.args) < 3 ):
496 rft.printErr("Error, userAdmin: invalid number of arguments")
497 rc=self.userAdminUsage(rft)
498 return(rc,None,False,None)
499
500 # get the <username> and <action> from args
501 userName=sc.args[1]
502 action=sc.args[2]
503 roleVal=""
504
505 # create the patch string, and identify property to set so that we can check that the resource has the property later
506 if( action=="enable"):
507 prop="Enabled"
508 patchData={prop: True}
509 elif( action=="disable"):
510 prop="Enabled"
511 patchData={prop: False}
512 elif( action=="unlock"):
513 prop="Locked"
514 patchData={prop: False}
515 elif( action=="setRoleId"):
516 if(len(sc.args) < 4):
517 rft.printErr("Error, userAdmin setRoleId: no <roleId> argument")
518 rc=self.userAdminUsage(rft)
519 return(rc,None,False,None)
520 else:
521 prop="RoleId"
522 roleVal=sc.args[3]
523 patchData={prop: roleVal}
524 else:
525 rft.printErr("Error: userAdmin: specified <action> not valid")
526 rc=self.userAdminUsage(rft)
527 return(rc,None,False,None)
528
529 # get Accounts collection
530 rc,r,j,d=op.getAccounts(sc,op, rft)
531 if( rc != 0): return(rc,r,False,None)
532
533 # find the Accounts entry for username, and verify we have that user
534 rft.gotMatchLevel2Optn=True
535 rft.matchLevel2Prop="UserName"
536 rft.matchLevel2Value=userName
537 path,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d) # this will return path to the acct as well as current resource in d
538 if( rc != 0):
539 rft.printErr("Error: username {} is not valid user".format(userName))
540 return(rc,None,False,None)
541 accountResponse=r
542
543 # verify the service supports the properties we need to set
544 if( not prop in d ):
545 rft.printErr("Error: userAdmin: property {} not in the remote service user account resource".format(prop))
546 return(8,None,False,None)
547
548 # if action=setRoleId, verify the service has that role
549 if( action=="setRoleId"):
550 # get Roles collection
551 rc,r,j,d=op.getRoles(sc,op, rft)
552 if( rc != 0): return(rc,r,False,None)
553 # check if the roleId specified is supported on this platform
554 rft.gotMatchLevel2Optn=True
555 rft.matchLevel2Prop="Id"
556 rft.matchLevel2Value=roleVal
557 path,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d) # this will return path to the acct as well as current resource in d
558 if( rc != 0):
559 rft.printErr("Error: roleId: {} is not supported on remote service".format(roleVal))
560 return(rc,None,False,None)
561
562 # send patch to set the properties
563 rc,r,j,d=rft.patchResource(rft, accountResponse, patchData)
564 if(rc==0):
565 rft.printVerbose(1," AccountService userAdmin {} {} :".format(action,roleVal),skip1=True, printV12=cmdTop)
566 respData={prop: d[prop]}
567 return(rc,r,j,respData)
568 else: return(rc,r,False,None)
569
570 def userAdminUsage(self,rft):
571 rft.printErr("Syntax: {} useradmin <username> {{enable|disable|unlock|{{setRoleId <roleId>}} }}".format(rft.program))
572 return(8)
573
574
575 # setusername <id> <username>
576 def setUsername(self, sc, op, rft, cmdTop=False, prop=None):
577 rft.printVerbose(4, "{}:{}: in operation".format(rft.subcommand, sc.operation))
578
579 # verify we have two addl args (<id> and <username>)
580 # create the patch string
581 # get Accounts collection
582 # then find the Accounts entry for the id, and verify we have that id
583 # verify the service supports the properties we need to set
584 # send patch to set the properties
585 # print("arglen:{}, arg0:{}, args:{}".format(len(sc.args),sc.args[0], sc.args))
586
587 # verify we have two additional args,
588 if (len(sc.args) != 3):
589 rft.printErr("Error, setusername: invalid number of arguments")
590 rc = self.setUsernameUsage(rft)
591 return (rc, None, False, None)
592
593 # get the <id> and <username> from args
594 idVal = sc.args[1]
595 userName = sc.args[2]
596
597 # create the patch string, and identify property to set so that we can check that the resource has the property later
598 prop = "UserName"
599 patchData = {prop: userName}
600
601 # get Accounts collection
602 rc, r, j, d = op.getAccounts(sc, op, rft)
603 if (rc != 0): return (rc, r, False, None)
604
605 # find the Accounts entry for id, and verify we have that id
606 rft.gotMatchLevel2Optn = True
607 rft.matchLevel2Prop = "Id"
608 rft.matchLevel2Value = idVal
609 path, rc, r, j, d = rft.getLevel2ResourceById(rft, r,
610 d) # this will return path to the acct as well as current resource in d
611 if (rc != 0):
612 rft.printErr("Error: Id {} is not a valid account Id".format(idVal))
613 return (rc, None, False, None)
614 accountResponse = r
615
616 # verify the service supports the properties we need to set
617 if (not prop in d):
618 rft.printErr("Error: setusername: property {} not in the remote service user account resource".format(prop))
619 return (8, None, False, None)
620
621 # send patch to set the properties
622 rc, r, j, d = rft.patchResource(rft, accountResponse, patchData)
623 if (rc == 0):
624 rft.printVerbose(1, " AccountService setusername {} {} :".format(idVal, userName), skip1=True,
625 printV12=cmdTop)
626 respData = {prop: d[prop]}
627 return (rc, r, j, respData)
628 else:
629 return (rc, r, False, None)
630
631 def setUsernameUsage(self, rft):
632 rft.printErr(
633 "Syntax: {} setusername <id> <username>".format(rft.program))
634 return (8)
635
636
637 # setpassword <username> <password>
638 def setPassword(self,sc,op,rft,cmdTop=False, prop=None):
639 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
640
641 # verify we have two addl args: <username> <passwd>.
642 # create the patch string
643 # get Accounts collection
644 # then find the Accounts entry for username, and verify we have that user
645 # send patch to set the password
646
647 # verify we have two addl arg,
648 if(len(sc.args) < 3 ):
649 rft.printErr("Error, setPassword: invalid number of arguments")
650 rft.printErr("Syntax: {} AccountService setPassword setpassword <username> <password>".format(rft.program))
651 return(8,None,False,None)
652
653 # get the <username> and <action> from args, and for the patchData
654 prop="Password"
655 userName=sc.args[1]
656 password=sc.args[2]
657 patchData={prop: password}
658
659 # get Accounts collection
660 rc,r,j,d=op.getAccounts(sc,op, rft)
661 if( rc != 0): return(rc,r,False,None)
662
663 # find the Accounts entry for username, and verify we have that user
664 rft.gotMatchLevel2Optn=True
665 rft.matchLevel2Prop="UserName"
666 rft.matchLevel2Value=userName
667 path,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d) # this will return path to the acct as well as current resource in d
668 if( rc != 0):
669 rft.printErr("Error: username {} is not valid user".format(userName))
670 return(rc,None,False,None)
671
672 # send patch to set the properties
673 # but set flag not to read the account back
674 # since the password has changed, this would fail for Basic Auth
675 rc,r,j,d=rft.patchResource(rft, r, patchData, getResponseAfterPatch=False )
676 if(rc==0):
677 rft.printVerbose(1," AccountService setPassword: successful",skip1=True, printV12=cmdTop)
678 respData=d
679 return(rc,r,j,respData)
680 else: return(rc,r,False,None)
681
682
683
684
685 # addRole <RoleId> <priviletes string> -- operation flow similar to addUser
686 #def setPassword(self,sc,op,rft,cmdTop=False, prop=None):
687 # rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
688
689
690
691 # deleteRole <RoleId> -- operation flow similar to deleteUser
692 #def setPassword(self,sc,op,rft,cmdTop=False, prop=None):
693 # rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
694
695
696
697
698 def examples(self,sc,op,rft,cmdTop=False,prop=None):
699 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
700 print(" {} -r<ip> AccountService # gets the AccountService".format(rft.program))
701 print(" {} -r<ip> AccountService patch {{ \"AccountLockoutThreshold\": 5 }} ]# set failed login lockout threshold".format(rft.program))
702 print(" {} -r<ip> AccountService Accounts # gets Accounts collection".format(rft.program))
703 print(" {} -r<ip> AccountService Accounts list # list Accounts to get Id, username, url for each account".format(rft.program))
704 print(" {} -r<ip> AccountService Accounts -mUserName:john # gets the Accounts member with username: john".format(rft.program))
705 print(" {} -r<ip> AccountService Roles list # list Roles collection to get RoleId, IsPredefined, & url for each role".format(rft.program))
706 print(" {} -r<ip> AccountService Roles -iAdministrator # gets the Roles member with RoleId=Administrator".format(rft.program))
707 print(" {} -r<ip> AccountService adduser john 12345 Administrator # add new user (john) w/ passwd \"12345\" and role: Administrator".format(rft.program))
708 print(" {} -r<ip> AccountService deleteuser john # delete user \"john\"s account".format(rft.program))
709 print(" {} -r<ip> AccountService useradmin john disable # disable user \"john\"s account".format(rft.program))
710 print(" {} -r<ip> AccountService useradmin john unlock # unlock user \"john\"s account".format(rft.program))
711 print(" {} -r<ip> AccountService setusername 3 alice # set username for account with id=3 to \"alice\"".format(rft.program))
712 return(0,None,False,None)
713
714
715 '''
716 TODO:
717 1. add "addRole" and "deleteRole" commands
718 2.
719
720
721 '''
722
723
724
725