Skip to content

Instantly share code, notes, and snippets.

@celediel
Last active March 15, 2020 05:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celediel/67e345ace49a917e43958c2a4ffe1401 to your computer and use it in GitHub Desktop.
Save celediel/67e345ace49a917e43958c2a4ffe1401 to your computer and use it in GitHub Desktop.
simple python sha512 password thing
import getpass
import hashlib
import anymarkup
def init(filename):
try:
users = anymarkup.parse_file(filename)
except:
users = []
finally:
# if the file exists but is empty, our users list won't be None, but also won't be what we want
# so just set it to an empty list also
if type(users) != type([]):
users = []
return users
def prompt_user(users):
username = getpass.getuser()
if not username:
username = input("Username: ")
else:
print(f"Username: {username}")
# TODO: check for new user before here
password = hashlib.sha512(getpass.getpass().encode())
# search users
try:
singleUser = next(item for item in users if item["username"] == username)
if singleUser["password"] == password.hexdigest():
# good password, do some stuff
return True
else:
# bad password, go away
return False
except StopIteration:
print(f"New user {username}")
# I really wish Python had do while
while True:
verifypass = hashlib.sha512(getpass.getpass("Verify Password: ").encode())
if verifypass.hexdigest() == password.hexdigest():
break
else:
print("you dun goofed, try again")
continue
users.append(dict(username=username, password=password.hexdigest()))
return True
def write_file(users, filename):
anymarkup.serialize_file(users, filename)
if __name__ == "__main__":
#! could store this better, but the password is hashed so whatever
# can be ini, json, json5, toml, xml or yaml
filename = "users.json"
# initialise list of users, will be empty list if filename doesn't exist
users = init(filename)
# returns true if new user, or existing user with good pass
# returns false if bad password
good = prompt_user(users)
if good:
print("Good job bud")
else:
print("That's a real ouchie bud")
# don't write nothing to the file
if len(users) != 0:
write_file(users, filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment