package auth import ( "fmt" "net/http" "os" "strconv" "github.com/gorilla/sessions" ) const ( SessionName = "markedit-session" UserIDKey = "user_id" ) var store *sessions.CookieStore // InitSessions initializes the session store func InitSessions() error { sessionSecret := os.Getenv("SESSION_SECRET") if sessionSecret == "" { return fmt.Errorf("SESSION_SECRET not configured") } if len(sessionSecret) < 32 { return fmt.Errorf("SESSION_SECRET must be at least 32 characters") } store = sessions.NewCookieStore([]byte(sessionSecret)) // Configure session options sessionSecure := os.Getenv("SESSION_SECURE") == "true" maxAge := 86400 // 24 hours default if maxAgeStr := os.Getenv("SESSION_MAX_AGE"); maxAgeStr != "" { if val, err := strconv.Atoi(maxAgeStr); err == nil { maxAge = val } } store.Options = &sessions.Options{ Path: "/", MaxAge: maxAge, HttpOnly: true, Secure: sessionSecure, SameSite: http.SameSiteLaxMode, } return nil } // GetSession retrieves the session for a request func GetSession(r *http.Request) (*sessions.Session, error) { return store.Get(r, SessionName) } // SaveSession saves the session func SaveSession(r *http.Request, w http.ResponseWriter, session *sessions.Session) error { return session.Save(r, w) } // SetUserID sets the user ID in the session func SetUserID(session *sessions.Session, userID int) { session.Values[UserIDKey] = userID } // GetUserID gets the user ID from the session func GetUserID(session *sessions.Session) (int, bool) { val, ok := session.Values[UserIDKey] if !ok { return 0, false } userID, ok := val.(int) return userID, ok } // ClearSession clears the session func ClearSession(session *sessions.Session) { session.Options.MaxAge = -1 for key := range session.Values { delete(session.Values, key) } }