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,7 +172,7 @@ func (s *Moonshark) initRunner() error {
// Configure session cookies
sessionManager.SetCookieOptions(
"MoonsharkID", // name
"MoonsharkSID", // name
"/", // path
"", // domain
false, // secure

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
if httpResp, ok := result.(*sandbox.HTTPResponse); ok {
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
@ -152,6 +155,33 @@ func (h *SessionHandler) addSessionCookie(resp *sandbox.HTTPResponse, sessionID
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
func GetSessionData(state *luajit.State) (string, map[string]any, bool) {
// Check if session was modified

View File

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