Being a newb to python I am not quite sure why I am getting inconsistent results. I register a user and the password in my table ends up being the hashed version. When the user updates his password, the password in the table ends up being the unhashed version. Obviously, I want the hashed version. What am I doing wrong? (I am using SQLAlchemy and mysql if that matters.)
I have the following:
def hash_password(password):
blah, blah, blah # hash my password here
return hashed_password
class User(Base):
__tablename__ = 'mytable'
email = Column('email')
_password = Column('password')
def _get_password(self):
return self._password
def _set_password(self, password):
self._password = hash_password(password)
password = property(_get_password, _set_password)
password = synonym('_password', descriptor=password)
def __init__(self, password="", email=""):
self.email = email
self.password = password
@classmethod
def register(cls, email, password):
return DBSession.add(User(email=email,password=password)) # this correctly hashes the password
@classmethod
def update(cls, email, password):
return DBSession.query(cls).filter(cls.email == email).update({'password': password}) #password ends up being the unhashed password
The issue here is the way that you are updating the password via your User.update
method. This method is skipping the ORM entirely and updating the row directly in the database. It should be obvious that the code to hash the password will not run when you do this. The User
model that you pasted is just fine and similar to what I use. You need to use it though. This means that to update a password you should load the user, and set their password.
user = DBSession.query(User).filter_by(email=email).first()
if user:
user.password = new_password
and later when the transaction is committed things will be the way you expect.