简体   繁体   English

Go GORM - BeforeUpdate 字段具有旧值

[英]Go GORM - BeforeUpdate fields have old values

I have a Go application with GORM and I'm trying to hash Users' password fields every time they are updated.我有一个带有 GORM 的 Go 应用程序,我正在尝试 hash 每次更新用户的密码字段。

To achieve this I'm using the BeforeUpdate hook provided by GORM.为此,我使用了 GORM 提供的BeforeUpdate挂钩。 The problem that I'm facing is that on the said hook the Password field for the user ( u.password ) has the old hashed password value that is already stored on the DB instead of the newPassword value that I'm updating it with.我面临的问题是,在上述钩子上,用户的Password字段( u.password )具有已存储在数据库中的旧哈希密码值,而不是我正在更新它的newPassword值。 So when I hash the password on the hook, I'm really just hashing the the already hashed old password.因此,当我将密码 hash 挂在钩子上时,我实际上只是在对已经散列的旧密码进行散列。

My BeforeUpdate hook:我的BeforeUpdate

func (u *User) BeforeUpdate(tx *gorm.DB) (err error) {
  if (tx.Statement.Changed("Password")) {
    bytePassword := []byte(u.Password) // Old password value here!
    passwordHash, err := bcrypt.GenerateFromPassword(bytePassword, bcrypt.DefaultCost)
    if (err != nil) { return err }
    tx.Statement.SetColumn("password", string(passwordHash))
  }
  return nil
}

And the update is triggered like this:更新是这样触发的:

var user models.User
err := db.First(&user, id).Error
if (err != nil) { log.Fatal(err) }
// Not sure how to access this "newPassword" value on the "BeforeUpdate" hook
err = db.Model(&user).Update("password", newPassword).Error
if (err != nil) { log.Fatal(err) }

You can get the new password value form the tx.Statement.Dest map.您可以从tx.Statement.Dest map 中获取新密码值。 This is the same map that SetColumn updates the value to.这与SetColumn将值更新到的 map 相同。

OR set the new password value before the actual update call.或在实际更新调用之前设置新密码值。

user.Password = newPassword
err = db.Model(&user).Updates(&user).Error

In this case old password will not be available at the hook.在这种情况下,旧密码将不可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM