From d53715378598a42b68819a327bf684e48955d2c3 Mon Sep 17 00:00:00 2001 From: Thomas Miceli <27960254+thomiceli@users.noreply.github.com> Date: Sat, 2 Nov 2024 01:05:43 +0100 Subject: [PATCH] Fix Markdown preview (#368) --- internal/cli/main.go | 2 +- internal/web/server.go | 7 ++++--- internal/web/test/server.go | 2 +- public/editor.ts | 6 +++++- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/internal/cli/main.go b/internal/cli/main.go index 9a403c3..4a96637 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -37,7 +37,7 @@ var CmdStart = cli.Command{ Initialize(ctx) - go web.NewServer(os.Getenv("OG_DEV") == "1", path.Join(config.GetHomeDir(), "sessions")).Start() + go web.NewServer(os.Getenv("OG_DEV") == "1", path.Join(config.GetHomeDir(), "sessions"), false).Start() go ssh.Start() <-stopCtx.Done() diff --git a/internal/web/server.go b/internal/web/server.go index 03010bf..f3d4850 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -164,7 +164,7 @@ type Server struct { dev bool } -func NewServer(isDev bool, sessionsPath string) *Server { +func NewServer(isDev bool, sessionsPath string, ignoreCsrf bool) *Server { dev = isDev flashStore = sessions.NewCookieStore([]byte("opengist")) encryptKey, _ := utils.GenerateSecretKey(filepath.Join(sessionsPath, "session-encrypt.key")) @@ -245,15 +245,16 @@ func NewServer(isDev bool, sessionsPath string) *Server { // Web based routes g1 := e.Group("") { - if !dev { + if !ignoreCsrf { g1.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{ TokenLookup: "form:_csrf,header:X-CSRF-Token", CookiePath: "/", CookieHTTPOnly: true, CookieSameSite: http.SameSiteStrictMode, })) + g1.Use(csrfInit) } - g1.Use(csrfInit) + g1.GET("/", create, logged) g1.POST("/", processCreate, logged) g1.POST("/preview", preview, logged) diff --git a/internal/web/test/server.go b/internal/web/test/server.go index 6463e41..ec9d6d0 100644 --- a/internal/web/test/server.go +++ b/internal/web/test/server.go @@ -33,7 +33,7 @@ type testServer struct { func newTestServer() (*testServer, error) { s := &testServer{ - server: web.NewServer(true, path.Join(config.GetHomeDir(), "tmp", "sessions")), + server: web.NewServer(true, path.Join(config.GetHomeDir(), "tmp", "sessions"), true), } go s.start() diff --git a/public/editor.ts b/public/editor.ts index 7a002cc..ae969b6 100644 --- a/public/editor.ts +++ b/public/editor.ts @@ -73,10 +73,14 @@ document.addEventListener("DOMContentLoaded", () => { } else { const formData = new FormData(); formData.append('content', editor.state.doc.toString()); + let csrf = document.querySelector('form#create input[name="_csrf"]').value fetch(`${baseUrl}/preview`, { method: 'POST', credentials: 'same-origin', - body: formData + body: formData, + headers: { + 'X-CSRF-Token': csrf + } }).then(r => r.text()).then(r => { let divpreview = dom.querySelector("div.preview") as HTMLElement; divpreview!.innerHTML = r;