Use transaction when necessary

This commit is contained in:
Jason Streifling 2024-03-06 15:37:59 +01:00
parent f1abb9d353
commit 3822a3f30e

View File

@ -89,12 +89,19 @@ func (db *DB) CheckPassword(id int64, pass string) error {
} }
func (db *DB) ChangePassword(id int64, oldPass, newPass string) error { func (db *DB) ChangePassword(id int64, oldPass, newPass string) error {
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("error starting transaction: %v", err)
}
if err := db.CheckPassword(id, oldPass); err != nil { if err := db.CheckPassword(id, oldPass); err != nil {
tx.Rollback()
return fmt.Errorf("error checking password: %v", err) return fmt.Errorf("error checking password: %v", err)
} }
newHashedPass, err := bcrypt.GenerateFromPassword([]byte(newPass), bcrypt.DefaultCost) newHashedPass, err := bcrypt.GenerateFromPassword([]byte(newPass), bcrypt.DefaultCost)
if err != nil { if err != nil {
tx.Rollback()
return fmt.Errorf("error creating password hash: %v", err) return fmt.Errorf("error creating password hash: %v", err)
} }
@ -104,9 +111,14 @@ func (db *DB) ChangePassword(id int64, oldPass, newPass string) error {
WHERE id = ? WHERE id = ?
` `
if _, err = db.Exec(query, string(newHashedPass), id); err != nil { if _, err = db.Exec(query, string(newHashedPass), id); err != nil {
tx.Rollback()
return fmt.Errorf("error updating password in DB: %v", err) return fmt.Errorf("error updating password in DB: %v", err)
} }
if err = tx.Commit(); err != nil {
return fmt.Errorf("error committing transaction: %v", err)
}
return nil return nil
} }