session fix attempt 1

This commit is contained in:
Sky Johnson 2025-04-08 22:54:16 -05:00
parent b2c1d1cb9f
commit 068fdc0617
3 changed files with 46 additions and 8 deletions

View File

@ -172,12 +172,12 @@ func (s *Moonshark) initRunner() error {
// Configure session cookies // Configure session cookies
sessionManager.SetCookieOptions( sessionManager.SetCookieOptions(
"MoonsharkID", // name "MoonsharkSID", // name
"/", // path "/", // path
"", // domain "", // domain
false, // secure false, // secure
true, // httpOnly true, // httpOnly
86400, // maxAge (1 day) 86400, // maxAge (1 day)
) )
// Set up runner options // Set up runner options

View File

@ -114,6 +114,9 @@ func (h *SessionHandler) postRequestHook(state *luajit.State, ctx *Context, resu
// Add session cookie to result if it's an HTTP response // Add session cookie to result if it's an HTTP response
if httpResp, ok := result.(*sandbox.HTTPResponse); ok { if httpResp, ok := result.(*sandbox.HTTPResponse); ok {
h.addSessionCookie(httpResp, modifiedID) h.addSessionCookie(httpResp, modifiedID)
} else if ctx != nil && ctx.RequestCtx != nil {
// Add cookie directly to the RequestCtx when result is not an HTTP response
h.addSessionCookieToRequestCtx(ctx.RequestCtx, modifiedID)
} }
return nil return nil
@ -152,6 +155,33 @@ func (h *SessionHandler) addSessionCookie(resp *sandbox.HTTPResponse, sessionID
resp.Cookies = append(resp.Cookies, cookie) resp.Cookies = append(resp.Cookies, cookie)
} }
func (h *SessionHandler) addSessionCookieToRequestCtx(ctx *fasthttp.RequestCtx, sessionID string) {
// Get cookie options
opts := h.manager.CookieOptions()
cookieName := opts["name"].(string)
// Create cookie
cookie := fasthttp.AcquireCookie()
defer fasthttp.ReleaseCookie(cookie)
cookie.SetKey(cookieName)
cookie.SetValue(sessionID)
cookie.SetPath(opts["path"].(string))
cookie.SetHTTPOnly(opts["http_only"].(bool))
cookie.SetMaxAge(opts["max_age"].(int))
// Optional cookie parameters
if domain, ok := opts["domain"].(string); ok && domain != "" {
cookie.SetDomain(domain)
}
if secure, ok := opts["secure"].(bool); ok {
cookie.SetSecure(secure)
}
ctx.Response.Header.SetCookie(cookie)
}
// GetSessionData extracts session data from Lua state // GetSessionData extracts session data from Lua state
func GetSessionData(state *luajit.State) (string, map[string]any, bool) { func GetSessionData(state *luajit.State) (string, map[string]any, bool) {
// Check if session was modified // Check if session was modified

View File

@ -1,6 +1,7 @@
package sessions package sessions
import ( import (
"Moonshark/core/utils/logger"
"crypto/rand" "crypto/rand"
"encoding/base64" "encoding/base64"
"sync" "sync"
@ -13,7 +14,7 @@ import (
const ( const (
// Default settings // Default settings
DefaultMaxSize = 100 * 1024 * 1024 // 100MB default cache size DefaultMaxSize = 100 * 1024 * 1024 // 100MB default cache size
DefaultCookieName = "MoonsharkID" DefaultCookieName = "MoonsharkSID"
DefaultCookiePath = "/" DefaultCookiePath = "/"
DefaultMaxAge = 86400 // 1 day in seconds DefaultMaxAge = 86400 // 1 day in seconds
) )
@ -61,20 +62,27 @@ func (sm *SessionManager) GetSession(id string) *Session {
data := sm.cache.Get(nil, []byte(id)) data := sm.cache.Get(nil, []byte(id))
if len(data) > 0 { if len(data) > 0 {
logger.Debug("Getting session %s", id)
// Session exists, unmarshal it // Session exists, unmarshal it
session := &Session{} session := &Session{}
if err := json.Unmarshal(data, session); err == nil { if err := json.Unmarshal(data, session); err == nil {
// Initialize mutex properly
session.mu = sync.RWMutex{}
// Update last accessed time // Update last accessed time
session.UpdatedAt = time.Now() session.UpdatedAt = time.Now()
// Store back with updated timestamp // Store back with updated timestamp
updatedData, _ := json.Marshal(session) updatedData, _ := json.Marshal(session)
sm.cache.Set([]byte(id), updatedData) sm.cache.Set([]byte(id), updatedData) // Use updatedData, not data
return session return session
} }
} }
logger.Debug("Session doesn't exist; creating it")
// Create new session // Create new session
session := NewSession(id) session := NewSession(id)
data, _ = json.Marshal(session) data, _ = json.Marshal(session)