switch to JSON mode of cli

pass around logger
This commit is contained in:
Nico Angelo
2023-04-21 16:50:33 +02:00
parent 0f518ab28d
commit ad1cc9f646
5 changed files with 25 additions and 22 deletions

View File

@ -7,44 +7,47 @@ class BitwardenCommandException(Exception):
pass
def get_secret_from_bitwarden(id):
return command_wrapper(command=f"get item {id}")
def get_secret_from_bitwarden(logger, id):
return command_wrapper(logger, command=f"get item {id}")
def unlock_bw(logger):
status_output = command_wrapper("status")
status = json.loads(status_output)['status']
status_output = command_wrapper(logger, "status", False)
status = status_output['data']['template']['status']
if status == 'unlocked':
logger.info("Already unlocked")
return
token_output = command_wrapper("unlock --passwordenv BW_PASSWORD")
tokens = token_output.split('"')[1::2]
os.environ["BW_SESSION"] = tokens[1]
token_output = command_wrapper(logger, "unlock --passwordenv BW_PASSWORD")
os.environ["BW_SESSION"] = token_output["data"]["raw"]
logger.info("Signin successful. Session exported")
def command_wrapper(command):
def command_wrapper(logger, command, use_success: bool = True):
system_env = dict(os.environ)
sp = subprocess.Popen(
[f"bw {command}"],
[f"bw --response {command}"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
shell=True,
env=system_env)
out, err = sp.communicate()
if err:
raise BitwardenCommandException(err)
return out.decode(encoding='UTF-8')
resp = json.loads(out.decode(encoding='UTF-8'))
if os.environ["DEBUG"] != None:
logger.info(resp)
if resp["success"] != None and (not use_success or (use_success and resp["success"] == True)):
return resp
logger.warn(resp)
return None
def parse_login_scope(secret_json, key):
return secret_json["login"][key]
return secret_json["data"]["login"][key]
def parse_fields_scope(secret_json, key):
if "fields" not in secret_json:
return None
for entry in secret_json["fields"]:
for entry in secret_json["data"]["fields"]:
if entry['name'] == key:
return entry['value']