2025-plovdiv-git/minimal_auth.py
2025-09-22 16:21:54 +03:00

51 lines
1.4 KiB
Python

import getpass # hides types characters, very useful
import json
import sys
import hashlib #base python lib to hash strings
def get_credentials():
username = input('Enter your username: ')
password = getpass.getpass('Enter your password: ')
return (username, password)
def authenticate(username, password, pwdb):
return hash_pass(password) == pwdb[username]
def hash_pass(text_password):
'''
hashes the user's string input to sha256
'''
password_in_bytes = bytearray(text_password, 'utf-8')
password_hashed = hashlib.sha256(password_in_bytes).hexdigest()
return password_hashed
def add_user(username, pwdb):
password = getpass.getpass(f'Enter password for {username}: ')
password_hashed = hash_pass(password)
pwdb[username] = password_hashed
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!')