feat: error handling when duplicate service

This commit is contained in:
Ruidy 2021-08-04 09:58:17 +02:00
parent d3116898e6
commit 183f739223
5 changed files with 33 additions and 10 deletions

View file

@ -49,6 +49,7 @@ def save(
numbers=numbers,
)
try:
password = pass_gen.generate_password(sqlite_repo, options)
typer.echo(typer.style(f"🔐 {password}", fg=typer.colors.GREEN, bold=True))
@ -58,11 +59,16 @@ def save(
return typer.echo(f"The password has been saved to: {file} 🗄")
utils.copy_to_clipboard(password)
return typer.echo("The password has been copied to your clipboard 😉\nPaste it using cmd + v")
return typer.echo(
"The password has been copied to your clipboard 😉\nPaste it using cmd + v"
)
except ValueError as error:
typer.echo(f"error: {error}", err=True)
@app.command()
def read() -> None:
sqlite_repo = sqlite.get_instance()
stored_passwords = sqlite_repo.list_all()
typer.echo([f"{p.service}: {p.password.get_secret_value()}" for p in stored_passwords])
stored_passwords = pass_gen.list_all_saved_passwords(sqlite_repo)
for p in stored_passwords:
typer.echo(f"{p.service}: {p.password.get_secret_value()}")

View file

@ -15,6 +15,9 @@ class FakeRepository:
Password(id=1, service="second", password=SecretStr("iK2ZWeqh")),
]
def exists(self, service: str) -> bool:
return False
@classmethod
def get_instance(cls) -> FakeRepository:
return FakeRepository()

View file

@ -21,9 +21,17 @@ class PasswordRepository:
def list_all(self) -> list[Password]:
return [
Password(id=row[0], service=row[1], password=row[2])
for row in self.db.execute("SELECT * FROM " "passwords").fetchall()
for row in self.db.execute("SELECT * FROM passwords").fetchall()
]
def exists(self, service: str) -> bool:
row = self.db.execute(
"SELECT EXISTS(SELECT 1 FROM passwords WHERE service=:service)",
{"service": service},
).fetchone()
return bool(row[0])
def get_instance() -> PasswordRepository:
db = sqlite.DB()

View file

@ -9,3 +9,6 @@ class Repository(Protocol):
def list_all(self) -> list[Password]:
...
def exists(self, service: str) -> bool:
...

View file

@ -17,6 +17,9 @@ class PassGenOptions(BaseModel):
def generate_password(repo: Repository, options: PassGenOptions) -> str:
if repo.exists(options.service):
raise ValueError("password for this service has already been set")
characters = _build_characters(symbols=options.symbols, numbers=options.numbers)
random_generator = _new_random_generator(options.seed)
password = "".join(random_generator.sample(characters, options.length))