From bd6f2159931b5877922efed11f7ea9c54b172379 Mon Sep 17 00:00:00 2001 From: JP Appel Date: Tue, 15 Oct 2024 23:56:50 -0400 Subject: Add authentication middleware --- middleware/auth.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 middleware/auth.go (limited to 'middleware/auth.go') diff --git a/middleware/auth.go b/middleware/auth.go new file mode 100644 index 0000000..93af421 --- /dev/null +++ b/middleware/auth.go @@ -0,0 +1,35 @@ +package middleware + +import ( + "crypto/sha256" + "crypto/subtle" + "net/http" + "nonsense-time/db" +) + +func BasicAuth(next http.Handler, authProvider db.AuthProvider) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + username, password, ok := r.BasicAuth() + + if !ok || !authProvider.UserExists(username) { + w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`) + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + + salt := authProvider.Salt(username) + input := []byte(password) + input = append(input, salt[:]...) + + passSaltHash := sha256.Sum256(input) + expectedSaltHash := authProvider.SaltedHash(username) + + if subtle.ConstantTimeCompare(expectedSaltHash[:], passSaltHash[:]) != 1 { + w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`) + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + + next.ServeHTTP(w, r) + }) +} -- cgit v1.2.3