refactor: replace session key strings with consts
Define KeyPlayerID, KeyUserID, and KeyNickname in the sessions package and use them across all handlers to avoid duplicated magic strings.
This commit is contained in:
@@ -14,6 +14,13 @@ import (
|
||||
"github.com/alexedwards/scs/v2"
|
||||
)
|
||||
|
||||
// Session key names.
|
||||
const (
|
||||
KeyPlayerID = "player_id"
|
||||
KeyUserID = "user_id"
|
||||
KeyNickname = "nickname"
|
||||
)
|
||||
|
||||
// SetupSessionManager creates a configured session manager backed by SQLite.
|
||||
// Returns the manager and a cleanup function the caller should defer.
|
||||
func SetupSessionManager(db *sql.DB) (*scs.SessionManager, func()) {
|
||||
@@ -38,12 +45,12 @@ func SetupSessionManager(db *sql.DB) (*scs.SessionManager, func()) {
|
||||
// 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")
|
||||
pid := sm.GetString(r.Context(), KeyPlayerID)
|
||||
if pid == "" {
|
||||
pid = player.GenerateID(8)
|
||||
sm.Put(r.Context(), "player_id", pid)
|
||||
sm.Put(r.Context(), KeyPlayerID, pid)
|
||||
}
|
||||
if userID := sm.GetString(r.Context(), "user_id"); userID != "" {
|
||||
if userID := sm.GetString(r.Context(), KeyUserID); userID != "" {
|
||||
return player.ID(userID)
|
||||
}
|
||||
return player.ID(pid)
|
||||
@@ -51,10 +58,10 @@ func GetPlayerID(sm *scs.SessionManager, r *http.Request) player.ID {
|
||||
|
||||
// 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")
|
||||
return sm.GetString(r.Context(), KeyUserID)
|
||||
}
|
||||
|
||||
// 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")
|
||||
return sm.GetString(r.Context(), KeyNickname)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user