From 28fcb55821dc45f21c068d92f3ad6133dad0260c Mon Sep 17 00:00:00 2001
From: ale <ale@incal.net>
Date: Fri, 20 Mar 2020 08:44:51 +0000
Subject: [PATCH] Handle the double-logout case more cleanly

Do not attempt to call backends (keystore) with empty usernames.
---
 server/http.go        | 10 ++++++----
 server/login/login.go |  6 ++++--
 2 files changed, 10 insertions(+), 6 deletions(-)

diff --git a/server/http.go b/server/http.go
index 6310b16..30a0c14 100644
--- a/server/http.go
+++ b/server/http.go
@@ -330,6 +330,10 @@ type logoutServiceInfo struct {
 
 // Logout handler. We generate a page that triggers child logout
 // requests to all the services the user is logged in to.
+//
+// Unauthenticated requests to /logout will fall through to this
+// handler, but auth.Username will be empty in that case. We are
+// still going to show the logout page to avoid confusion.
 func (h *Server) handleLogout(w http.ResponseWriter, req *http.Request) {
 	auth, ok := login.GetAuth(req.Context())
 	if !ok {
@@ -337,8 +341,6 @@ func (h *Server) handleLogout(w http.ResponseWriter, req *http.Request) {
 		return
 	}
 
-	//
-
 	var svcs []logoutServiceInfo
 	for _, svc := range auth.Services {
 		svcs = append(svcs, logoutServiceInfo{
@@ -354,8 +356,8 @@ func (h *Server) handleLogout(w http.ResponseWriter, req *http.Request) {
 		"IncludeLogoutScripts": true,
 	}
 
-	// Close the keystore.
-	if h.keystore != nil {
+	// Close the keystore (only if the session had a valid username).
+	if h.keystore != nil && auth.Username != "" {
 		var shard string
 		if auth.UserInfo != nil {
 			shard = auth.UserInfo.Shard
diff --git a/server/login/login.go b/server/login/login.go
index fd540fd..5d25d14 100644
--- a/server/login/login.go
+++ b/server/login/login.go
@@ -190,8 +190,10 @@ func (l *Login) ServeHTTP(w http.ResponseWriter, req *http.Request) {
 		// wrapped handler. Note that the Auth object will still
 		// contain valid data, but Authenticated will be set to false.
 		if req.URL.Path == l.urlFor("/logout") {
-			log.Printf("logging out user %s", session.Username)
-			session.Authenticated = false
+			if session.Authenticated {
+				log.Printf("logging out user %s", session.Username)
+				session.Authenticated = false
+			}
 			session.Delete()
 		} else if !session.Authenticated {
 			// Save the current URL in the session for later redirect.
-- 
GitLab