From 0402a6ff9c22c1d4ef38d9b60a276c8a6dc7c258 Mon Sep 17 00:00:00 2001 From: Gregory Wells Date: Wed, 1 Apr 2026 00:09:04 -0400 Subject: [PATCH] make the session logic a little more concrete --- src/main/main.go | 2 +- src/main/session.go | 26 ++++++++++++-------------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/src/main/main.go b/src/main/main.go index cd30983..2224cc4 100644 --- a/src/main/main.go +++ b/src/main/main.go @@ -234,7 +234,7 @@ func logoutHandler(w http.ResponseWriter, r *http.Request) { } logging.Infof("handling logout event for %s", sessionData.data.Username) - deleteSession(token) + deleteSession(hashSession(token)) http.Redirect(w, r, "/login", http.StatusSeeOther) } diff --git a/src/main/session.go b/src/main/session.go index b883de6..5a0bf1e 100644 --- a/src/main/session.go +++ b/src/main/session.go @@ -19,7 +19,7 @@ type SessionData struct { } var ( - sessions = make(map[string]SessionData) + sessions = make(map[string]*SessionData) sessionMutex sync.Mutex ) @@ -46,8 +46,7 @@ func createSession(userData *UserData) *http.Cookie { return nil } - tokenEncoded := sha256.Sum256([]byte(token)) - tokenEncodedString := string(tokenEncoded[:]) + encodedToken := hashSession(token) sessionMutex.Lock() defer sessionMutex.Unlock() @@ -55,7 +54,7 @@ func createSession(userData *UserData) *http.Cookie { if userData != nil { loggedIn = true } - sessions[tokenEncodedString] = SessionData{ + sessions[encodedToken] = &SessionData{ data: userData, timeCreated: time.Now(), CSRFToken: CSRFToken, @@ -81,26 +80,25 @@ func validateSession(r *http.Request) (bool, *SessionData) { return false, &SessionData{} } token := cookie.Value - - tokenEncoded := sha256.Sum256([]byte(token)) - tokenEncodedString := string(tokenEncoded[:]) + token = hashSession(token) sessionMutex.Lock() - sessionData, exists := sessions[tokenEncodedString] + sessionData, exists := sessions[token] sessionMutex.Unlock() if !exists || !sessionData.loggedIn { return false, &SessionData{} } logging.Infof("Validated session for %s", sessionData.data.Username) - return true, &sessionData + return true, sessionData +} + +func hashSession(session_id string) string { + tokenEncoded := sha256.Sum256([]byte(session_id)) + return base64.RawURLEncoding.EncodeToString(tokenEncoded[:]) } func deleteSession(session_id string) { sessionMutex.Lock() - - tokenEncoded := sha256.Sum256([]byte(session_id)) - tokenEncodedString := string(tokenEncoded[:]) - - delete(sessions, tokenEncodedString) + delete(sessions, session_id) sessionMutex.Unlock() }