From efcb6ae933a95e588ef0895b985e616ea64a0f7c Mon Sep 17 00:00:00 2001 From: Tiziano Zito Date: Thu, 22 Aug 2024 11:49:59 +0200 Subject: [PATCH] simplified solution --- auth.py | 29 ++++++----------------------- 1 file changed, 6 insertions(+), 23 deletions(-) diff --git a/auth.py b/auth.py index a845cc8..5408393 100644 --- a/auth.py +++ b/auth.py @@ -39,19 +39,11 @@ def add_user(username, pwdb): return pwdb def read_pwdb(pwdb_path): - # try to read from the database - # if anything happens, report the error! if not pwdb_path.exists(): - initialize_pwdb(pwdb_path) - try: + pwdb = {} + else: with open(pwdb_path, 'rt') as pwdb_file: pwdb = json.load(pwdb_file) - except json.decoder.JSONDecodeError as exc: - # this happens when the json data is invalid - raise Exception(f'Invalid database {pwdb_path}: {exc}') - except Exception as exc: - # this is a catch-all condition - raise Exception(f'Unkown error reading {pwdb_path}: {exc}') return pwdb def write_pwdb(pwdb, pwdb_path): @@ -72,9 +64,6 @@ def get_salt(): salt_chars = random.choices(CHARS, k=SALT_LENGTH) return ''.join(salt_chars) -def initialize_pwdb(pwdb_path): - write_pwdb({}, pwdb_path) - def main(pwdb_path): # load the password database from file pwdb = read_pwdb(pwdb_path) @@ -87,17 +76,11 @@ def main(pwdb_path): # ask for credentials username, password = get_credentials() - - if username not in pwdb: - print('Wrong username!') - return - - # try to authenticate - if authenticate(username, password, pwdb): - print('Successfully authenticated!') + if username not in pwdb or not authenticate(username, password, pwdb): + print('Wrong username or password!') else: - # report wrong password - print('Wrong password!') + print('Successfully authenticated!') + return if __name__ == '__main__':