From 0710eabe7b2754cf420eff12deb85b4318af0388 Mon Sep 17 00:00:00 2001 From: Jonathan Wren Date: Sat, 8 Oct 2022 15:53:10 -0700 Subject: [PATCH] keep logic for password attemps inside the class that uses it --- jrnl/encryption/BasePasswordEncryption.py | 16 +++++++++++++--- jrnl/prompt.py | 11 +++-------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/jrnl/encryption/BasePasswordEncryption.py b/jrnl/encryption/BasePasswordEncryption.py index 9485fb463..d25d2cd11 100644 --- a/jrnl/encryption/BasePasswordEncryption.py +++ b/jrnl/encryption/BasePasswordEncryption.py @@ -1,7 +1,11 @@ # Copyright © 2012-2022 jrnl contributors # License: https://www.gnu.org/licenses/gpl-3.0.html from jrnl.encryption.BaseEncryption import BaseEncryption +from jrnl.exception import JrnlException from jrnl.keyring import get_keyring_password +from jrnl.messages import Message +from jrnl.messages import MsgStyle +from jrnl.messages import MsgText from jrnl.prompt import create_password from jrnl.prompt import prompt_password @@ -34,12 +38,18 @@ def encrypt(self, text: str) -> bytes: def decrypt(self, text: bytes) -> str: if not self.password: self._prompt_password() + while (result := self._decrypt(text)) is None: self._prompt_password() return result def _prompt_password(self) -> None: - self._attempts, self.password = prompt_password( - self._attempts, self._max_attempts - ) + if self._attempts >= self._max_attempts: + raise JrnlException( + Message(MsgText.PasswordMaxTriesExceeded, MsgStyle.ERROR) + ) + + first_try = self._attempts == 0 + self.password = prompt_password(first_try=first_try) + self._attempts += 1 diff --git a/jrnl/prompt.py b/jrnl/prompt.py index 988ae98a9..23af983a1 100644 --- a/jrnl/prompt.py +++ b/jrnl/prompt.py @@ -43,22 +43,17 @@ def create_password(journal_name: str) -> str: return pw -def prompt_password(attempts: int, max_attempts: int) -> tuple[int, str]: - if attempts >= max_attempts: - raise JrnlException(Message(MsgText.PasswordMaxTriesExceeded, MsgStyle.ERROR)) - - if attempts > 0: +def prompt_password(first_try: bool = True) -> str: + if not first_try: print_msg(Message(MsgText.WrongPasswordTryAgain, MsgStyle.WARNING)) - attempts += 1 return ( - attempts, print_msg( Message(MsgText.Password, MsgStyle.PROMPT), get_input=True, hide_input=True, ) - or "", + or "" )