import argparse import json import urllib.request class Ungleich_Config(object): def __init__(self, parser, parents): self.parser = parser self.parser['add'] = self.parser['sub'].add_parser( 'config-add', help="Add user to configuration file", parents=[parents]) self.parser['list'] = self.parser['sub'].add_parser( 'config-list', help="list users in configuration file", parents=[parents]) self.parser['delete'] = self.parser['sub'].add_parser( 'config-delete', help="remove a user in configuration file", parents=[parents]) self.parser['add'].add_argument('--name', help='otp name', required=True) self.parser['add'].add_argument('--realm', help='otp realm', required=True) self.parser['add'].add_argument('--seed', help='otp seed', required=True) self.parser['delete'].add_argument('--id', help='user ID to remove', required=True) self.parser['list'].set_defaults(func=self._list_users) self.parser['add'].set_defaults(func=self._add_user) self.parser['delete'].set_defaults(func=self._delete_user) def _add_user(self, args): try: f = open('users.json', 'r') json_info = json.loads(f.read()) if len(json_info) > 0: with open('users.json', 'w') as fp: last_id = int(list(json_info.keys())[-1]) + 1 json_info[last_id] = {"name": args.name, "realm": args.realm, "seed": args.seed} json.dump(json_info, fp) print('User added.') else: with open('users.json', 'w') as fp: d = {"name": args.name, "realm": args.realm, "seed": args.seed} json.dump({"1": d}, fp) print('User added.') except FileNotFoundError: with open('users.json', 'w') as fp: d = {"name": args.name, "realm": args.realm, "seed": args.seed} json.dump({"1": d}, fp) print('User added.') def _list_users(self, args): try: f = open('users.json', 'r') json_info = json.loads(f.read()) for key, value in json_info.items(): print('{}: {}'.format(key, value['name'])) except FileNotFoundError: print('No users loaded.') def _delete_user(self, args): try: f = open('users.json', 'r') json_info = json.loads(f.read()) try: del json_info[args.id] f = open('users.json', 'w') x = 1 for i in list(json_info.keys()): json_info[str(x)] = json_info.pop(i) x+=1 f.write(json.dumps(json_info)) f.close() except KeyError: print("No user with such id.") except FileNotFoundError: print('No users loaded.')