在这段代码中,第一个函数是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")
}
}
1条答案
按热度按时间g6baxovj1#
根据文档,这是
bycrypt.CompareHashAndPassword()
的func模式:要使用它,您需要将
hashedPassword
(存储在数据库中的散列密码)作为函数调用的第一个参数。然后从request param中取
password
作为第二个参数的值。在
Findaccount()
上,语句bcrypt.CompareHashAndPassword()
的第一个参数由Account.Password
填充,Account.Password
是存储在数据库中的散列密码。