0

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
4

2 回答 2

5

这里的问题是您通过您的User.update方法更新密码的方式。此方法完全跳过 ORM 并直接在数据库中更新行。很明显,当您执行此操作时,散列密码的代码将不会运行。您粘贴的User模型很好,与我使用的相似。不过,您需要使用它。这意味着要更新密码,您应该加载用户并设置他们的密码。

user = DBSession.query(User).filter_by(email=email).first()
if user:
    user.password = new_password

稍后当事务提交时,事情将按照您的预期进行。

于 2012-10-21T15:31:34.377 回答
1

您应该将密码哈希存储在数据库中,因此模型的字段必须包含哈希值,而不是原始密码。要设置密码,您应该使用进行散列并将散列设置为实例的方法。要检查密码是否正确,您应该对用户定义的密码进行哈希处理,并将结果与​​存储在您的实例中的哈希值进行比较。Yo 将无法从哈希中解码密码 - 这是不安全的。

class User(Base):
    __tablename__ = 'user'

    email = Column('email', String(80))
    password = Column('password', String(80))

    def set_password(raw_password):
        self.password = hash(raw_password)

    def check_password(raw_password):
        return self.password == hash(raw_password)
于 2012-10-20T18:01:39.450 回答