Corrected transaction for ChangePassword()

This commit is contained in:
Jason Streifling 2024-03-06 16:51:08 +01:00
parent 3822a3f30e
commit ea45da66b7

View File

@ -94,9 +94,21 @@ func (db *DB) ChangePassword(id int64, oldPass, newPass string) error {
return fmt.Errorf("error starting transaction: %v", err)
}
if err := db.CheckPassword(id, oldPass); err != nil {
var queriedPass string
getQuery := `
SELECT password
FROM users
WHERE id = ?
`
row := tx.QueryRow(getQuery, id)
if err := row.Scan(&queriedPass); err != nil {
tx.Rollback()
return fmt.Errorf("error checking password: %v", err)
return fmt.Errorf("error reading password from DB: %v", err)
}
if err := bcrypt.CompareHashAndPassword([]byte(queriedPass), []byte(oldPass)); err != nil {
tx.Rollback()
return fmt.Errorf("incorrect password: %v", err)
}
newHashedPass, err := bcrypt.GenerateFromPassword([]byte(newPass), bcrypt.DefaultCost)
@ -105,12 +117,12 @@ func (db *DB) ChangePassword(id int64, oldPass, newPass string) error {
return fmt.Errorf("error creating password hash: %v", err)
}
query := `
setQuery := `
UPDATE users
SET password = ?
WHERE id = ?
`
if _, err = db.Exec(query, string(newHashedPass), id); err != nil {
if _, err = tx.Exec(setQuery, string(newHashedPass), id); err != nil {
tx.Rollback()
return fmt.Errorf("error updating password in DB: %v", err)
}