Login with GORM with intercalated return between ID and 0

Asked

Viewed 29 times

2

Guys, I’m learning to code in the GO language, and I made an api with a login system.

func Authenticate(db *gorm.DB, auth models.UserAuthForm) uint {
    hasher.Write([]byte(auth.Password))
    pass_hash := hex.EncodeToString(hasher.Sum(nil))
    user := models.User{}

    db.Select("id").Where("pass_hash = ? AND email = ?", pass_hash, auth.Email).First(&user)
    hasher.Reset()
    return user.ID
}

This function is called inside a controller with POST method in login is represented by the Struct:

type UserAuthForm struct {
    Email    string `json:"email" form:"email" binding:"required"`
    Password string `json:"password" form:"password" binding:"required"`
}

that uid represents the id returned and a cookie is saved in Session

uid := crud.Authenticate(db, login)
if uid != 0 {
    sess := sessions.Default(c)
    sess.Set("user", crud.SaveCookieId(db, uid))
    sess.Save()
    c.JSON(200, gin.H{"Message": "Success!"})
    return
}
c.JSON(401, gin.H{"Error": "Failed!"})
return

My real problem is that when I try to log in, first the return is:

{
    "Message": "Success!"
}

but when he tries again, he returns:

{
    "Error": "Failed!"
}

and if I try again, it returns to be successful and so remains interspersed

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.