func SignInValidation(sl validator.StructLevel) {
payload := sl.Current().Interface().(SignInPayload)
user := services.FindUserByEmail(payload.Email)
if user.ID == 0 {
sl.ReportError(payload.Email, "Email", "email", "email", "Unregistered user!")
}
fmt.Println(user.Password, payload.Password)
err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(payload.Password))
fmt.Println(err)
if err != nil {
sl.ReportError(payload.Password, "Password", "password", "password", "Password is incorrect!")
}
}
Above is my code to sign in user. I encrypt user's password and save to db. Then to user login, compare hashed password and plain password. And I am getting an error crypto/bcrypt: hashedPassword is not the hash of the given password
. Whats wrong?
Update: This is my sign-up endpoint and logic to hash pasword:
func SignUpMain(ctx iris.Context) orm.Users {
activationToken := uuid.NewString()
payload := orm.Users{
ActivationToken: activationToken,
ActivationState: constants.UserActivationState["PENDING"],
ActivationTokenExpiresAt: time.Now().Add(time.Hour * 24 * 7),
LastLoginAt: time.Now(),
LastLoginFromIpAddress: ctx.RemoteAddr(),
}
if err := ctx.ReadJSON(&payload); err != nil {
ctx.StopExecution()
panic("Error to read JSON")
}
hash := hashedPassword(payload.Password)
payload.Password = string(hash)
user := services.SignUp(payload)
services.GenerateToken(user, ctx)
// Notification
libs.SlackNewUser(user)
mailer.SendActivationAccountMail(user, activationToken)
return user
}
func hashedPassword(password string) []byte {
hash, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
panic("Error to encrypt password")
}
return hash
}
CodePudding user response:
First, you need to check whether the data are sent correctly.Just print the payload and check the values are mapping correctly. Next, you need to check whether checking is done correctly
bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
Must be the already hashed PW ^ ^ Plain Text Password to compare
CodePudding user response:
The problem occurs when I omit the password from the model.
Password string `gorm:"column:password;type:varchar(255)" json:"-"`
So payload.Password
is always an empty string. I just added it to the json tag. And, the problem has been solved.
Password string `gorm:"column:password;type:varchar(255)" json:"password"`