问题描述
作为 python 的新手,我不太清楚为什么我得到的结果不一致.我注册了一个用户,我的表中的密码最终是散列版本.当用户更新他的密码时,表中的密码最终是未散列的版本.显然,我想要散列版本.我究竟做错了什么?(如果重要的话,我正在使用 SQLAlchemy 和 mysql.)
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.)
我有以下几点:
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
推荐答案
这里的问题是您通过 User.update
方法更新密码的方式.此方法完全跳过 ORM 并直接在数据库中更新行.很明显,当您这样做时,散列密码的代码将不会运行.您粘贴的 User
模型很好,与我使用的相似.你需要使用它.这意味着要更新密码,您应该加载用户并设置他们的密码.
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.
这篇关于更新时密码未加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!