Fix dupe logs and add remove password by id

This commit is contained in:
Antonio J. Delgado 2024-11-17 10:52:18 +02:00
parent f7384d8ae1
commit d1275b5076

View file

@ -22,6 +22,7 @@ import click
import click_config_file
import passpy
import secretstorage
from contextlib import closing
from cryptography.fernet import Fernet
try:
import requests
@ -99,7 +100,10 @@ def decrypt_item(item_key, item, key='label'):
class NextcloudHandler:
'''Handle Nextcloud Password API'''
def __init__(self, params):
self._init_log(params)
if 'logger' in params:
self._log = params['logger']
else:
self._init_log(params)
self.http = 'https'
self.timeout = params.get('timeout', 3)
self.ssl = True
@ -270,6 +274,7 @@ class NextcloudHandler:
"last_update": -1,
"cached_passwords": []
}
closing(secretstorage.dbus_init())
def _write_cache(self):
self.debug(
@ -282,6 +287,7 @@ class NextcloudHandler:
cipher_suite = Fernet(self.encryption_pass)
encrypted_cache = cipher_suite.encrypt(bytes(json.dumps(self.cache), 'utf-8'))
cache_file.write(encrypted_cache)
closing(secretstorage.dbus_init())
def _safer_obj(self, obj, fields=None):
if fields is None:
@ -1002,6 +1008,7 @@ class NcPasswordClient:
"timeout": timeout,
"cache_duration": cache_duration,
"https_proxy": https_proxy,
"logger": self._log,
}
self.nc = NextcloudHandler(params)
@ -1076,10 +1083,22 @@ class NcPasswordClient:
}
)
def delete_password(self, name):
def delete_password(self, name, password_id):
'''Delete a password'''
if name is not None:
field = 'label'
elif password_id is not None:
field = 'id'
else:
self.error(
{
"action": "delete_password",
"message": "You must indicate a name or a password id to delete"
}
)
sys.exit(2)
for password in self.nc.list_passwords():
if password['label'] == name:
if password[field] == name:
safer_obj = dict(password, **{ 'password': '***' })
self.debug(
{ "action": "delete_password", "object": safer_obj }
@ -1091,7 +1110,7 @@ class NcPasswordClient:
self.warning(
{
"action": "delete_password",
"message": "Password with that name doesn't exist",
"message": f"Password with that {field} doesn't exist",
"object": name
}
)
@ -1331,12 +1350,13 @@ def create_password(ctx, obj, update):
ctx.obj['NcPasswordClient'].create_password(json.loads(obj), update)
@cli.command()
@click.option('--name', '-n', required=True, help='Name of the password to delete')
@click.option('--name', '-n', help='Name of the password to delete')
@click.option('--password-id', '-i', help='ID of the password to delete')
@click_config_file.configuration_option()
@click.pass_context
def delete_password(ctx, name):
def delete_password(ctx, name, password_id):
'''Delete a password'''
ctx.obj['NcPasswordClient'].delete_password(name)
ctx.obj['NcPasswordClient'].delete_password(name, password_id)
@cli.command()
@click.option('--name', '-n', required=True, help='Name of the passwords folder to create')