【发布时间】:2021-07-30 07:15:53
【问题描述】:
在这段代码中,第一个函数是Findaccount(),它将在数据库中查找电子邮件地址和作为哈希值出现的密码。所以CompareHashAndPassword()比较哈希和密码。
现在在handler.go 文件中,我有一个名为loginData() 的函数,它允许用户登录。我这里有个问题。我调用了database.Findaccount(email, password, hash) 函数,但它只是验证电子邮件地址而不验证
正确的密码,并给我false 消息。
但是,如果我像 database.Findaccount(email, "1234", hash) 这样调用函数,它会验证电子邮件和密码。
如何解决这个问题,因为我无法记住每个密码。
db.go
func Findaccount(myEmail, myPassword, hash string) bool {
collection := Connect.Database("WebApp2").Collection("dataStored")
if err := collection.FindOne(context.TODO(), bson.M{"email": myEmail}).Decode(&Account); err != nil {
fmt.Println("Enter the correct email or password")
}
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(myPassword))
return err == nil
}
handler.go
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
func loginData(w http.ResponseWriter, r *http.Request) {
email := r.FormValue("email")
password := r.FormValue("password")
hash, _ := HashPassword(password)
match := database.Findaccount(email, password, hash) // here is a problem
if match == false {
fmt.Println("false")
} else {
fmt.Println("true")
}
}
【问题讨论】:
-
您应该从
Account中获取hash -
这里是哈希
$2a$04$28kZ/RY.BhGyWQvWPAngduAhoZPjrsyE6zEDCufu1gClsHpCyXJeW