Switch to passlib for password hashing and verification

at some point now, can remove the 'salt' column too
This commit is contained in:
Lance Edgar 2017-11-09 21:35:15 -06:00
parent 30636fcfcf
commit 4af93ac405
2 changed files with 8 additions and 18 deletions

View file

@ -26,13 +26,15 @@ Authentication & Authorization
from __future__ import unicode_literals, absolute_import from __future__ import unicode_literals, absolute_import
import bcrypt from passlib.context import CryptContext
import six
from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import NoResultFound
from rattail.db import model from rattail.db import model
password_context = CryptContext(schemes=['bcrypt'])
def authenticate_user(session, userobj, password): def authenticate_user(session, userobj, password):
""" """
Attempt to authenticate a user. Attempt to authenticate a user.
@ -53,28 +55,15 @@ def authenticate_user(session, userobj, password):
except NoResultFound: except NoResultFound:
user = None user = None
if user and user.active and user.password is not None: if user and user.active and user.password is not None:
# apparently bcrypt's hashpw() doesn't like Unicode if password_context.verify(password, user.password):
if isinstance(password, six.text_type):
password = password.encode('utf_8')
salt = user.salt.encode('utf_8')
try:
authenticated = (bcrypt.hashpw(password, salt) == user.password)
except UnicodeEncodeError:
authenticated = False
if authenticated:
return user return user
return None
def set_user_password(user, password): def set_user_password(user, password):
""" """
Set a user's password. Set a user's password.
""" """
# apparently bcrypt's hashpw() doesn't like Unicode user.password = password_context.hash(password)
if isinstance(password, six.text_type):
password = password.encode('utf_8')
user.salt = bcrypt.gensalt()
user.password = bcrypt.hashpw(password, user.salt)
def special_role(session, uuid, name): def special_role(session, uuid, name):

View file

@ -162,7 +162,8 @@ else:
extras['auth'] = [ extras['auth'] = [
# #
# package # low high # package # low high
'passlib', # 1.7.1
'py-bcrypt', # 0.2 'py-bcrypt', # 0.2
] ]