diff options
author | Julien Dessaux | 2025-01-06 00:41:32 +0100 |
---|---|---|
committer | Julien Dessaux | 2025-01-06 00:41:32 +0100 |
commit | 6e069484cb0a911ba541e07bf04331fadbb76612 (patch) | |
tree | 3457c759d54ae91e5ac1e64fe0bbf9c4b8ac18f0 /pkg/webui/sessions.go | |
parent | feat(tfstated): add syscall.SIGTERM handling (diff) | |
download | tfstated-6e069484cb0a911ba541e07bf04331fadbb76612.tar.gz tfstated-6e069484cb0a911ba541e07bf04331fadbb76612.tar.bz2 tfstated-6e069484cb0a911ba541e07bf04331fadbb76612.zip |
feat(webui): bootstrap session handling and login process
Diffstat (limited to '')
-rw-r--r-- | pkg/webui/sessions.go | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/pkg/webui/sessions.go b/pkg/webui/sessions.go new file mode 100644 index 0000000..6d492d5 --- /dev/null +++ b/pkg/webui/sessions.go @@ -0,0 +1,55 @@ +package webui + +import ( + "context" + "errors" + "fmt" + "net/http" + + "git.adyxax.org/adyxax/tfstated/pkg/database" + "git.adyxax.org/adyxax/tfstated/pkg/model" +) + +const cookieName = "tfstated" + +func sessionsMiddleware(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) { + cookie, err := r.Cookie(cookieName) + if err != nil && !errors.Is(err, http.ErrNoCookie) { + errorResponse(w, http.StatusInternalServerError, fmt.Errorf("failed to get request cookie \"%s\": %w", cookieName, err)) + return + } + if err == nil { + if len(cookie.Value) != 36 { + http.SetCookie(w, &http.Cookie{ + Name: cookieName, + Value: "", + Quoted: false, + Path: "/", + MaxAge: 0, // remove invalid cookie + HttpOnly: true, + SameSite: http.SameSiteStrictMode, + Secure: true, + }) + } else { + session, err := db.LoadSessionById(cookie.Value) + if err != nil { + errorResponse(w, http.StatusInternalServerError, err) + return + } + if !session.IsExpired() { + if err := db.TouchSession(cookie.Value); err != nil { + errorResponse(w, http.StatusInternalServerError, err) + return + } + ctx := context.WithValue(r.Context(), model.SessionContextKey{}, session) + next.ServeHTTP(w, r.WithContext(ctx)) + return + } + } + } + next.ServeHTTP(w, r) + }) + } +} |