From dd49fe4a41e5c90abdaa9ab07ecf56979f9530d9 Mon Sep 17 00:00:00 2001
From: ale <ale@incal.net>
Date: Mon, 12 Dec 2022 12:00:30 +0000
Subject: [PATCH] Add CORS support (defaulting to true)

Serve Access-Control-Allow-Origin: * headers on /sso_login and
/sso_logout endpoints, to allow sso auto-renewal on AJAX requests.
---
 httpsso/handler.go | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/httpsso/handler.go b/httpsso/handler.go
index e750f33..e90b6a0 100644
--- a/httpsso/handler.go
+++ b/httpsso/handler.go
@@ -76,6 +76,8 @@ type SSOWrapper struct {
 	sc           *securecookie.SecureCookie
 	serverURL    string
 	serverOrigin string
+
+	EnableCORS bool
 }
 
 // NewSSOWrapper returns a new SSOWrapper that will authenticate users
@@ -96,6 +98,7 @@ func NewSSOWrapper(serverURL string, pkey []byte, domain string, sessionAuthKey,
 		sc:           sc,
 		serverURL:    serverURL,
 		serverOrigin: originFromURL(serverURL),
+		EnableCORS:   true,
 	}, nil
 }
 
@@ -172,7 +175,7 @@ func (s *SSOWrapper) handleLogin(w http.ResponseWriter, req *http.Request, servi
 		HttpOnly: true,
 	})
 
-	http.Redirect(w, req, d, http.StatusFound)
+	s.redirectWithCORS(w, req, d)
 }
 
 func (s *SSOWrapper) handleLogout(w http.ResponseWriter, req *http.Request) {
@@ -209,7 +212,14 @@ func (s *SSOWrapper) redirectToLogin(w http.ResponseWriter, req *http.Request, s
 	v.Set("n", nonce)
 	v.Set("g", strings.Join(groups, ","))
 	loginURL := s.serverURL + "?" + v.Encode()
-	http.Redirect(w, req, loginURL, http.StatusFound)
+	s.redirectWithCORS(w, req, loginURL)
+}
+
+func (s *SSOWrapper) redirectWithCORS(w http.ResponseWriter, req *http.Request, uri string) {
+	if s.EnableCORS {
+		w.Header().Set("Access-Control-Allow-Origin", "*")
+	}
+	http.Redirect(w, req, uri, http.StatusFound)
 }
 
 // Extract the URL path from the service specification. The result
-- 
GitLab