Rendere l'output di phicli json #3

Open
blallo wants to merge 4 commits from json-serialize-output into master
Showing only changes of commit 8fbf159461 - Show all commits

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from pprint import pformat as pp from pprint import pformat as pp
from getpass import getpass from getpass import getpass
import json
from phi.config import get_config from phi.config import get_config
from phi.logging import setup_logging, get_logger from phi.logging import setup_logging, get_logger
@ -11,21 +12,36 @@ from phi.ldap.group import get_group_by_cn, get_all_groups, add_group_member
log = get_logger(__name__) log = get_logger(__name__)
JSON_ENC = json.JSONEncoder()
SHOW_PASSWORDS = False
@cli.register('dispaly user fields', ['user identifier'])
def sanitize(obj):
if isinstance(obj, list):
return [sanitize(el) for el in obj]
elif isinstance(obj, dict):
return dict((sanitize(k), sanitize(v)) for k, v in obj.items())
elif isinstance(obj, bytes):
return [hex(el) for el in list(obj)]
return obj
@cli.register("dispaly user fields", ["user identifier"])
def showuser(uid): def showuser(uid):
user = get_user_by_uid(client, uid) user = get_user_by_uid(client, uid)
if user is None: if user is None:
print('User {} not found'.format(uid)) print("User {} not found".format(uid))
return return
if not SHOW_PASSWORDS:
user.pop("password")
print(pp(user)) print(JSON_ENC.encode(sanitize(user)))
@cli.register('add a new user', ['user identifier']) @cli.register("add a new user", ["user identifier"])
def adduser(uid): def adduser(uid):
def ask(prompt, default): def ask(prompt, default):
full_prompt = '{} [{}] '.format(prompt, default) full_prompt = "{} [{}] ".format(prompt, default)
return input(full_prompt) or default return input(full_prompt) or default
user = get_user_by_uid(client, uid) user = get_user_by_uid(client, uid)
@ -33,14 +49,14 @@ def adduser(uid):
print("User {} already existing".format(uid)) print("User {} already existing".format(uid))
return return
cn = ask('Common name:', uid) cn = ask("Common name:", uid)
sn = ask('Last name:', uid) sn = ask("Last name:", uid)
mail = ask('Mail:', '{}@localhost'.format(uid)) mail = ask("Mail:", "{}@localhost".format(uid))
password = getpass() password = getpass()
pass_check = getpass('Retype password: ') pass_check = getpass("Retype password: ")
if password != pass_check: if password != pass_check:
print('Password not matching') print("Password not matching")
return return
add_user(client, uid, cn, sn, mail, password) add_user(client, uid, cn, sn, mail, password)
@ -51,80 +67,80 @@ def adduser(uid):
print(pp(user)) print(pp(user))
@cli.register('delete an user', ['user identifier']) @cli.register("delete an user", ["user identifier"])
def deluser(uid): def deluser(uid):
check = input('Are you sure? [y/N] ') or 'N' check = input("Are you sure? [y/N] ") or "N"
if check.lower() != 'y': if check.lower() != "y":
print('Ok then') print("Ok then")
return return
user = get_user_by_uid(client, uid) user = get_user_by_uid(client, uid)
if user is not None: if user is not None:
delete_user(client, user) delete_user(client, user)
print('Done') print("Done")
else: else:
print('User {} not found'.format(uid)) print("User {} not found".format(uid))
@cli.register('show a group', ['group common name']) @cli.register("show a group", ["group common name"])
def showgroup(cn): def showgroup(cn):
group = get_group_by_cn(client, cn) group = get_group_by_cn(client, cn)
if group is None: if group is None:
print('Group {} not found'.format(gcn)) print("Group {} not found".format(gcn))
return return
print(pp(group)) print(pp(group))
@cli.register('list all groups') @cli.register("list all groups")
def listgroups(): def listgroups():
groups = get_all_groups(client) groups = get_all_groups(client)
for group in groups: for group in groups:
print(group['cn']) print(group["cn"])
@cli.register('add an user to a group', @cli.register("add an user to a group", ["user identifier", "group common name"])
['user identifier', 'group common name'])
def addtogroup(uid, gcn): def addtogroup(uid, gcn):
user = get_user_by_uid(client, uid) user = get_user_by_uid(client, uid)
group = get_group_by_cn(client, gcn) group = get_group_by_cn(client, gcn)
if user is None: if user is None:
print('User {} not found'.format(uid)) print("User {} not found".format(uid))
return return
if group is None: if group is None:
print('Group {} not found'.format(gcn)) print("Group {} not found".format(gcn))
return return
if uid in group['members']: if uid in group["members"]:
print('User {} is already in group {}'.format(uid, gcn)) print("User {} is already in group {}".format(uid, gcn))
return return
add_group_member(client, group, user) add_group_member(client, group, user)
if __name__ == '__main__': if __name__ == "__main__":
cli.add_arg('--config', 'config.yml', 'custom configuration file') cli.add_arg("--config", "config.yml", "custom configuration file")
cli.add_flag("--show-passwords", "show the passwords bytes")
args = cli.get_args() args = cli.get_args()
config_file = args['config'] config_file = args["config"]
SHOW_PASSWORDS = args["show_passwords"]
config_file, config = get_config(config_file) config_file, config = get_config(config_file)
setup_logging(config.get('logging', {})) setup_logging(config.get("logging", {}))
log.info("Using configuration at '{}':\n{}" log.info("Using configuration at '{}':\n{}".format(config_file, pp(config)))
.format(config_file, pp(config)))
# TODO: check fields in config # TODO: check fields in config
client = phi.ldap.client.Client(**config['ldap']) client = phi.ldap.client.Client(**config["ldap"])
log.info('Opening LDAP client') log.info("Opening LDAP client")
client.open() client.open()
log.info('Arguments: {}'.format(pp(args))) log.info("Arguments: {}".format(pp(args)))
cli.run(args) cli.run(args)
log.info('Closing LDAP client') log.info("Closing LDAP client")
client.close() client.close()