From 132990e985751e40c263224a62983c8013409a36 Mon Sep 17 00:00:00 2001 From: xengineering Date: Sat, 27 Jun 2026 21:21:45 +0200 Subject: Switch Register() and Authenticate() to sql.Tx Using sql.Tx (database transactions) instead of a plain database has the advantage that the caller can wrap multiple library calls into one transaction. This guarantees that no database entries change between the library calls which is critical to prevent race conditions. --- password.go | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) (limited to 'password.go') diff --git a/password.go b/password.go index edbeb7a..9be347a 100644 --- a/password.go +++ b/password.go @@ -12,34 +12,30 @@ const ( bcryptCost = 12 ) -func Register(db *sql.DB, username, password string) error { +func Register(tx *sql.Tx, username, password string) error { hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost) if err != nil { return err } - err = Transaction(db, func(tx *sql.Tx) error { - _, err := tx.Exec( - `INSERT INTO users (username, password_bcrypt) VALUES(?, ?);`, - username, - hash, - ) - return err - }) + _, err = tx.Exec( + `INSERT INTO users (username, password_bcrypt) VALUES(?, ?);`, + username, + hash, + ) return err } -func Authenticate(db *sql.DB, username, password string) error { +func Authenticate(tx *sql.Tx, username, password string) error { var hash []byte - err := Transaction(db, func(tx *sql.Tx) error { - row := tx.QueryRow( - `SELECT password_bcrypt from users WHERE username=?;`, - username, - ) - - return row.Scan(&hash) - }) + + row := tx.QueryRow( + `SELECT password_bcrypt from users WHERE username=?;`, + username, + ) + + err := row.Scan(&hash) if err != nil { return fmt.Errorf("Failed to get password hash from database: %w", err) } -- cgit v1.3.1