aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/middleware/auth.go
diff options
context:
space:
mode:
authorJP Appel <jeanpierre.appel01@gmail.com>2024-10-15 23:56:50 -0400
committerJP Appel <jeanpierre.appel01@gmail.com>2024-10-15 23:57:30 -0400
commitbd6f2159931b5877922efed11f7ea9c54b172379 (patch)
tree12bca5fbf677a0d0146686128cdcb39800536206 /middleware/auth.go
parent9b6e79c40b98d8e36e4b7f5e1cc6f6a9f0feabbc (diff)
Add authentication middlewaredashboard
Diffstat (limited to 'middleware/auth.go')
-rw-r--r--middleware/auth.go35
1 files changed, 35 insertions, 0 deletions
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)
+ })
+}