refactor: extract session helpers for player identity resolution

Add GetPlayerID, GetUserID, GetNickname to the sessions package.
Remove the inline player-ID-from-session pattern duplicated across
every handler in c4game and snakegame, and the local getPlayerID
helper in snakegame.
This commit is contained in:
Ryan Hamamura
2026-03-02 19:16:09 -10:00
parent 063b03ce25
commit 7eadfbbb0c
3 changed files with 67 additions and 79 deletions

View File

@@ -1,4 +1,5 @@
// Package sessions configures the SCS session manager backed by SQLite.
// Package sessions configures the SCS session manager and provides
// helpers for resolving player identity from the session.
package sessions
import (
@@ -7,6 +8,8 @@ import (
"net/http"
"time"
"github.com/ryanhamamura/c4/player"
"github.com/alexedwards/scs/sqlite3store"
"github.com/alexedwards/scs/v2"
)
@@ -30,3 +33,28 @@ func SetupSessionManager(db *sql.DB) (*scs.SessionManager, func()) {
return sessionManager, cleanup
}
// GetPlayerID returns the current player's identity from the session.
// Authenticated users get their user UUID; guests get a random ID that
// is generated and persisted on first access.
func GetPlayerID(sm *scs.SessionManager, r *http.Request) player.ID {
pid := sm.GetString(r.Context(), "player_id")
if pid == "" {
pid = player.GenerateID(8)
sm.Put(r.Context(), "player_id", pid)
}
if userID := sm.GetString(r.Context(), "user_id"); userID != "" {
return player.ID(userID)
}
return player.ID(pid)
}
// GetUserID returns the authenticated user's UUID, or empty string for guests.
func GetUserID(sm *scs.SessionManager, r *http.Request) string {
return sm.GetString(r.Context(), "user_id")
}
// GetNickname returns the player's display name from the session.
func GetNickname(sm *scs.SessionManager, r *http.Request) string {
return sm.GetString(r.Context(), "nickname")
}