50 lines
1.5 KiB
Python
50 lines
1.5 KiB
Python
import getpass # hides types characters, very useful
|
|
import json
|
|
import sys
|
|
import hashlib # python standard lib for hashing
|
|
|
|
def get_credentials():
|
|
username = input('Enter your username: ')
|
|
password = getpass.getpass('Enter your password: ')
|
|
return (username, password)
|
|
|
|
# add a function that hashes the password
|
|
def hash_password(password):
|
|
return hashlib.sha256(f'{password}'.encode()).hexdigest()
|
|
|
|
def authenticate(username, password, pwdb):
|
|
correct_password = pwdb[username]
|
|
# add this line to hash the entered password to then compared with the stored password
|
|
attempted_password = hash_password(password)
|
|
return correct_password == attempted_password
|
|
|
|
def add_user(username, pwdb):
|
|
password = getpass.getpass(f'Enter password for {username}: ')
|
|
# hash the password before saving to the database
|
|
pwdb[username] = hash_password(password)
|
|
return pwdb
|
|
|
|
def read_pwdb(pwdb_path):
|
|
try:
|
|
pwdb_file = open(pwdb_path, 'rt')
|
|
pwdb = json.load(pwdb_file)
|
|
except Exception:
|
|
pwdb = {}
|
|
return pwdb
|
|
|
|
def write_pwdb(pwdb, pwdb_path):
|
|
pwdb_file = open(pwdb_path, 'wt')
|
|
json.dump(pwdb, pwdb_file)
|
|
|
|
pwdb_path = 'pwdb.json'
|
|
pwdb = read_pwdb(pwdb_path)
|
|
|
|
if len(sys.argv) > 1:
|
|
pwdb = add_user(sys.argv[1], pwdb)
|
|
write_pwdb(pwdb, pwdb_path)
|
|
else:
|
|
username, password = get_credentials()
|
|
if username not in pwdb or not authenticate(username, password, pwdb):
|
|
print('Wrong username or password!')
|
|
else:
|
|
print('Successfully authenticated!')
|