From bf6181764bcd1b70a161e83153f2a344764be174 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20=C5=A0ediv=C3=BD?= Date: Thu, 25 Mar 2021 10:29:28 +0100 Subject: [PATCH] clear cookie if non-existent session. --- internal/api/router.go | 6 ++++-- internal/api/session.go | 2 +- internal/session/auth.go | 19 +++++++------------ internal/types/session.go | 2 +- 4 files changed, 13 insertions(+), 16 deletions(-) diff --git a/internal/api/router.go b/internal/api/router.go index 477e94da..45b6fe2c 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -69,10 +69,12 @@ func (api *ApiManagerCtx) Authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { session, err := api.sessions.Authenticate(r) if err != nil { + api.sessions.CookieClearToken(w, r) utils.HttpUnauthorized(w, err) - } else { - next.ServeHTTP(w, auth.SetSession(r, session)) + return } + + next.ServeHTTP(w, auth.SetSession(r, session)) }) } diff --git a/internal/api/session.go b/internal/api/session.go index e45b8cc3..60c7b4ce 100644 --- a/internal/api/session.go +++ b/internal/api/session.go @@ -49,7 +49,7 @@ func (api *ApiManagerCtx) Logout(w http.ResponseWriter, r *http.Request) { return } - api.sessions.CookieClearToken(w) + api.sessions.CookieClearToken(w, r) utils.HttpSuccess(w, true) } diff --git a/internal/session/auth.go b/internal/session/auth.go index 5619a234..6e6eaaa1 100644 --- a/internal/session/auth.go +++ b/internal/session/auth.go @@ -25,20 +25,15 @@ func (manager *SessionManagerCtx) CookieSetToken(w http.ResponseWriter, token st }) } -func (manager *SessionManagerCtx) CookieClearToken(w http.ResponseWriter) { - sameSite := http.SameSiteDefaultMode - if manager.config.CookieSecure { - sameSite = http.SameSiteNoneMode +func (manager *SessionManagerCtx) CookieClearToken(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie(manager.config.CookieName) + if err != nil { + return } - http.SetCookie(w, &http.Cookie{ - Name: manager.config.CookieName, - Value: "", - Expires: time.Unix(0, 0), - Secure: manager.config.CookieSecure, - SameSite: sameSite, - HttpOnly: true, - }) + cookie.Value = "" + cookie.Expires = time.Unix(0, 0) + http.SetCookie(w, cookie) } func (manager *SessionManagerCtx) Authenticate(r *http.Request) (types.Session, error) { diff --git a/internal/types/session.go b/internal/types/session.go index 19d22031..cf68df51 100644 --- a/internal/types/session.go +++ b/internal/types/session.go @@ -51,6 +51,6 @@ type SessionManager interface { ImplicitHosting() bool CookieSetToken(w http.ResponseWriter, token string) - CookieClearToken(w http.ResponseWriter) + CookieClearToken(w http.ResponseWriter, r *http.Request) Authenticate(r *http.Request) (Session, error) }