summaryrefslogtreecommitdiff
path: root/pkg/basic_auth
diff options
context:
space:
mode:
authorJulien Dessaux2024-11-14 01:34:29 +0100
committerJulien Dessaux2024-11-14 01:34:29 +0100
commit3d8812fbd0091d2ef636949628c52bf9f48617a6 (patch)
tree00755c8903497ad7abaaffffbbaa4a37fdf41a03 /pkg/basic_auth
parentchore(tfstated): rename state "name" to "path" for consistency (diff)
downloadtfstated-3d8812fbd0091d2ef636949628c52bf9f48617a6.tar.gz
tfstated-3d8812fbd0091d2ef636949628c52bf9f48617a6.tar.bz2
tfstated-3d8812fbd0091d2ef636949628c52bf9f48617a6.zip
feat(tfstated): implement HTTP basic auth
Diffstat (limited to 'pkg/basic_auth')
-rw-r--r--pkg/basic_auth/middleware.go39
1 files changed, 39 insertions, 0 deletions
diff --git a/pkg/basic_auth/middleware.go b/pkg/basic_auth/middleware.go
new file mode 100644
index 0000000..108124f
--- /dev/null
+++ b/pkg/basic_auth/middleware.go
@@ -0,0 +1,39 @@
+package basic_auth
+
+import (
+ "context"
+ "net/http"
+ "time"
+
+ "git.adyxax.org/adyxax/tfstated/pkg/database"
+)
+
+func Middleware(db *database.DB) func(http.Handler) http.Handler {
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ username, password, ok := r.BasicAuth()
+ if !ok {
+ w.Header().Set("WWW-Authenticate", `Basic realm="tfstated", charset="UTF-8"`)
+ http.Error(w, "Unauthorized", http.StatusUnauthorized)
+ return
+ }
+ account, err := db.LoadAccountByUsername(username)
+ if err != nil {
+ http.Error(w, "Internal Server Error", http.StatusInternalServerError)
+ return
+ }
+ if password != account.Password {
+ http.Error(w, "Forbidden", http.StatusForbidden)
+ return
+ }
+ now := time.Now().UTC()
+ _, err = db.Exec(`UPDATE accounts SET last_login = ? WHERE id = ?`, now.Unix(), account.Id)
+ if err != nil {
+ http.Error(w, "Internal Server Error", http.StatusInternalServerError)
+ return
+ }
+ ctx := context.WithValue(r.Context(), "account", account)
+ next.ServeHTTP(w, r.WithContext(ctx))
+ })
+ }
+}