From 6a17f83719de72befcf8e7a8103fa79b6b8cd372 Mon Sep 17 00:00:00 2001 From: ASPP Student Date: Mon, 28 Aug 2023 15:22:23 +0300 Subject: [PATCH] make a file and authenticate if user exists --- auth.py | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/auth.py b/auth.py index b946a1f..51c90b4 100644 --- a/auth.py +++ b/auth.py @@ -1,5 +1,6 @@ import json import getpass +import os PATH = "./pwdb.json" @@ -8,14 +9,24 @@ def get_credentials(): password = getpass.getpass("Password: ") return username, password -def read_pwdb(): - with open(PATH, "rt") as f: - pwdb = json.load(f) +def read_pwdb(username, password): + if os.path.exists(PATH): + pwdb={} + with open(PATH, "rt") as f: + pwdb = json.load(f) + authenticate(username, password, pwdb) + else: + pwdb=add_user(username, password, pwdb={}) + write_pwdb(pwdb) + print("First user added!") return pwdb + def write_pwdb(pwdb): with open(PATH, "w") as f: - json.dump(pwdb, f) + f.write(json.dumps(pwdb)) + f.write("\n") + f.close() def authenticate(username, password, pwdb): @@ -23,16 +34,16 @@ def authenticate(username, password, pwdb): if password == pwdb[username]: print("Successfully authenticated!") else: - print("Wrong Password") + print("Wrong password") else: pwdb = add_user(username, password, pwdb) write_pwdb(pwdb) + print("New user added") def add_user(username, password, pwdb): pwdb[username] = password return pwdb username, password = get_credentials() -pwdb = read_pwdb() -authenticate(username, password, pwdb) +pwdb = read_pwdb(username, password)