import hashlib import json import os def load_db(db_path): # If the file provided does not exist, return an empty dict (a blank database) if not os.path.isfile(db_path): return {} with open(db_path, 'r') as reader: db = reader.read() return json.loads(db) def login(db_path): print("Welcome to Password Generator, please sign in.") username = input("Enter username? ") password = input("Enter password? ") db = load_db(db_path) valid = True # 1. Does the provided username exist? if db.get(username): user_pass = db.get(username)['secret'] # 2. Ok, we know the user's hashed password. Now let's hash the input and compare: if hashlib.sha224(password.encode('utf-8')).hexdigest() != user_pass: valid = False else: valid = False if valid: print("You are logged in!") else: print("Invalid Password! or Username!") def register(db_path): selection = input("What to do? (register/login) ") selection = selection.lower() if selection == 'register': user_info = { 'name': None, 'secret': None, 'email': None, } user_info['name'] = input("Username? ") user_info['secret'] = input("Password? ") user_info['email'] = input("What's your email address? ") # Load the database db = load_db(db_path) # Check if the provided username is already taken if db.get(user_info['name']): raise Exception('Username already taken ({})'.format(user_info['name'])) # If it's not taken, create a slot for it in the DB db[user_info['name']] = user_info # ...but be sure to hash the password: user_info['secret'] = hashlib.sha224(user_info['secret'].encode('utf-8')).hexdigest() # Update the database file with open(db_path, 'w') as writer: print('Updating the contents of the datase') print(db) writer.write(json.dumps(db)) elif selection == 'login': login(db_path) else: print('Invalid option. No soup for you!') register('user_db.json')
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question