【问题标题】:Password not getting encrypted when I update更新时密码未加密
【发布时间】:2012-10-11 01:28:36
【问题描述】:

作为 python 的新手,我不太清楚为什么会得到不一致的结果。 我注册了一个用户,我的表中的密码最终成为散列版本。当用户更新他的密码时,表中的密码最终是未散列的版本。显然,我想要散列版本。我究竟做错了什么? (如果这很重要,我正在使用 SQLAlchemy 和 mysql。)

我有以下几点:

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

【问题讨论】:

    标签: python sqlalchemy pyramid


    【解决方案1】:

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

    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)
    

    【讨论】:

      【解决方案2】:

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

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

      稍后当事务提交时,事情就会如你所愿。

      【讨论】:

      • 我的回答是你应该停止使用User.update 方法。这不是通过 SQLAlchemy 与数据库交互的好模式。
      • 你是对的。我接受了另一个答案,因为我得到了它的工作,但我从不觉得这是正确的方法。
      猜你喜欢
      • 1970-01-01
      • 2023-02-03
      • 2010-10-23
      • 2020-10-25
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      相关资源
      最近更新 更多