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. --- handlers.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) (limited to 'handlers.go') diff --git a/handlers.go b/handlers.go index 0ff2f26..4b86ad5 100644 --- a/handlers.go +++ b/handlers.go @@ -62,11 +62,15 @@ func ApiAuthentication(db *sql.DB) http.Handler { return } - err = Authenticate(db, data.Username, data.Password) - if err != nil { - log.Printf("Bad password on authentication of user '%s'.", data.Username) - w.WriteHeader(http.StatusUnauthorized) - return - } + _ = Transaction(db, func(tx *sql.Tx) error { + err := Authenticate(tx, data.Username, data.Password) + if err != nil { + log.Printf("Bad password on authentication of user '%s'.", data.Username) + w.WriteHeader(http.StatusUnauthorized) + return fmt.Errorf("Authentication failed.") + } + + return nil + }) }) } -- cgit v1.3.1