From 5ad7131df28dde5665590fe63f5a408decd5c0fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mats=20T=C3=B6rnberg?= Date: Wed, 3 Dec 2025 19:51:22 +0100 Subject: [PATCH] clear cookie if failing --- cmd/checkout/pool-server.go | 12 ++++++++++-- cmd/checkout/utils.go | 30 +++++++++++++++++++++--------- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/cmd/checkout/pool-server.go b/cmd/checkout/pool-server.go index a87f805..4862578 100644 --- a/cmd/checkout/pool-server.go +++ b/cmd/checkout/pool-server.go @@ -210,7 +210,14 @@ func (s *CheckoutPoolServer) StartCheckoutHandler(w http.ResponseWriter, r *http } // Create checkout with same ID as cart - checkoutId := checkout.CheckoutId(cartId) + var checkoutId checkout.CheckoutId = cart.MustNewCartId() + cookie, err := r.Cookie(checkoutCookieName) + if err == nil { + parsed, ok := cart.ParseCartId(cookie.Value) + if ok { + checkoutId = parsed + } + } // Initialize checkout with cart state wrapped in Any cartStateAny := &messages.InitializeCheckout{ @@ -225,13 +232,14 @@ func (s *CheckoutPoolServer) StartCheckoutHandler(w http.ResponseWriter, r *http result, err := s.ApplyLocal(r.Context(), checkoutId, cartStateAny) if err != nil { + setCheckoutCookie(w, 0, r.TLS != nil) logger.Error("failed to initialize checkout", "error", err) http.Error(w, "failed to initialize checkout", http.StatusInternalServerError) return } // Set checkout cookie - setCheckoutCookie(w, result.Result.Id, r.TLS != nil) + setCheckoutCookie(w, checkoutId, r.TLS != nil) if err := s.WriteResult(w, result.Result); err != nil { logger.Error("failed to write result", "error", err) diff --git a/cmd/checkout/utils.go b/cmd/checkout/utils.go index 9b2e398..b897ca3 100644 --- a/cmd/checkout/utils.go +++ b/cmd/checkout/utils.go @@ -68,15 +68,27 @@ func (a *CheckoutPoolServer) reserveInventory(ctx context.Context, grain *checko const checkoutCookieName = "checkoutid" func setCheckoutCookie(w http.ResponseWriter, checkoutId checkout.CheckoutId, tls bool) { - http.SetCookie(w, &http.Cookie{ - Name: checkoutCookieName, - Value: checkoutId.String(), - Secure: tls, - HttpOnly: true, - Path: "/", - Expires: time.Now().AddDate(0, 0, 14), - SameSite: http.SameSiteLaxMode, - }) + if checkoutId == 0 { + http.SetCookie(w, &http.Cookie{ + Name: checkoutCookieName, + Value: checkoutId.String(), + Secure: tls, + HttpOnly: true, + Path: "/", + Expires: time.Unix(0, 0), + SameSite: http.SameSiteLaxMode, + }) + } else { + http.SetCookie(w, &http.Cookie{ + Name: checkoutCookieName, + Value: checkoutId.String(), + Secure: tls, + HttpOnly: true, + Path: "/", + Expires: time.Now().AddDate(0, 0, 14), + SameSite: http.SameSiteLaxMode, + }) + } } func CookieCheckoutIdHandler(fn func(w http.ResponseWriter, r *http.Request, checkoutId checkout.CheckoutId) error) func(w http.ResponseWriter, r *http.Request) {