Skip to content

Instantly share code, notes, and snippets.

@ShawnMilo
Last active August 29, 2015 14:19
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 ShawnMilo/732adb5028d35fabffdf to your computer and use it in GitHub Desktop.
Save ShawnMilo/732adb5028d35fabffdf to your computer and use it in GitHub Desktop.
from hashlib import sha512
from uuid import uuid4
from redis import StrictRedis
__all__ = (
'hash_password', 'create_user', 'login_is_valid',
)
conn = StrictRedis()
def hash_password(password, salt=None):
"""
Given a password, return a salted, hashed
version of it.
When verifying an existing password, the
salt must be provided or all hope is lost.
"""
if salt is None:
salt = uuid4().hex
hash = sha512(salt + password).hexdigest()
return "{0}${1}".format(salt, hash)
def create_user(email, password):
"""
Add a user to the database.
"""
conn.setex(email, 120, hash_password(password))
def login_is_valid(email, password):
"""
Compare the user's raw input to the
hashed value in the database to determine
whether the password is valid.
"""
db_pass = conn.get(email)
if db_pass is None:
return False
salt = db_pass.split('$')[0]
hashed = hash_password(password, salt)
if hashed == db_pass:
return True
else:
return False
if __name__ == "__main__":
# Test data.
email = "admin@example.com"
password = "sntaoehusn"
# Nothing in database, should be false.
assert login_is_valid(email, password) == False
# Create, then it should work.
create_user(email, password)
assert login_is_valid(email, password) == True
# Invalid passwords are invalid.
assert login_is_valid(email, password + "foo") == False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment