go Web入门登录出错
在 go Web入门 中,按流程走完, 注册的账号登出再次登录会提示登录错误,控制台返回
`crypto/bcrypt: hashedPassword is not the hash of the given password`
通过debug发现是因为在创建用户时,触发了beforeSave()
和 beforeCreate()
两个钩子:
创建时,首先在 beforeSave()
中对password
字段进行了hash处理,然后在beforeCreate()
中没有对password
进行判断,又进行了第二次hash转换,最后存入数据库中的时候一个经过两次hash转换的password
,登录时bcrypt比对时,则每次都会返回密码不匹配,所以只需要在 beforeCreate()
中也加入对password
字段是否hash转换的判断既可,如下图:
// BeforeCreate GORM 的模型钩子,创建模型前调用
func (user *User) BeforeCreate(tx *gorm.DB) (err error) {
if !password.IsHashed(user.Password) {
user.Password, err = password.Hash(user.Password)
logger.LogError(err)
}
return
}
修改后用户可正常登录。
推荐文章: