From 326f53f681d025efc71673ad3bd7db407f8e5ddf Mon Sep 17 00:00:00 2001 From: GHIFARI160 Date: Tue, 27 May 2025 16:31:17 -0500 Subject: [PATCH] Middleware.RequireAccount: handle error before reading session m.RequireAccount checks if session is nil and only handles error when it is. This is not idiomatic. Also, ErrNoSession is handled with direct equality comparison. So, handle errors and protect against nil Session before adding it to the request context. And when checking for ErrNoSession, do so with errors.Is. This way, custom implementations of SessionProvider can wrap ErrNoSession, if they so choose. --- samlsp/middleware.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/samlsp/middleware.go b/samlsp/middleware.go index 93a3cf95..9f1e3e81 100644 --- a/samlsp/middleware.go +++ b/samlsp/middleware.go @@ -3,6 +3,7 @@ package samlsp import ( "bytes" "encoding/xml" + "errors" "net/http" "github.com/crewjam/saml" @@ -115,17 +116,16 @@ func (m *Middleware) ServeACS(w http.ResponseWriter, r *http.Request) { func (m *Middleware) RequireAccount(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { session, err := m.Session.GetSession(r) - if session != nil { - r = r.WithContext(ContextWithSession(r.Context(), session)) - handler.ServeHTTP(w, r) - return - } - if err == ErrNoSession { + if err != nil && errors.Is(err, ErrNoSession) { m.HandleStartAuthFlow(w, r) return + } else if err != nil || session == nil { + m.OnError(w, r, err) + return } - m.OnError(w, r, err) + r = r.WithContext(ContextWithSession(r.Context(), session)) + handler.ServeHTTP(w, r) }) }