2024-12-10 13:40:41 -05:00
|
|
|
package context
|
2024-12-05 20:36:58 -05:00
|
|
|
|
|
|
|
|
import (
|
2024-12-13 15:10:27 -05:00
|
|
|
"github.com/onsonr/sonr/internal/gateway/models"
|
2024-12-05 20:36:58 -05:00
|
|
|
"github.com/onsonr/sonr/pkg/common"
|
2024-12-06 21:31:20 -05:00
|
|
|
"github.com/segmentio/ksuid"
|
2024-12-05 20:36:58 -05:00
|
|
|
)
|
|
|
|
|
|
2024-12-13 15:10:27 -05:00
|
|
|
// initSession initializes or loads an existing session
|
|
|
|
|
func (s *HTTPContext) initSession() error {
|
2024-12-06 21:31:20 -05:00
|
|
|
sessionID := s.getOrCreateSessionID()
|
|
|
|
|
|
|
|
|
|
// Try to load existing session
|
2024-12-13 15:10:27 -05:00
|
|
|
var sess models.Session
|
2024-12-06 21:31:20 -05:00
|
|
|
result := s.db.Where("id = ?", sessionID).First(&sess)
|
|
|
|
|
if result.Error != nil {
|
|
|
|
|
// Create new session if not found
|
2024-12-13 15:10:27 -05:00
|
|
|
sess = models.Session{
|
|
|
|
|
ID: sessionID,
|
|
|
|
|
BrowserName: s.GetBrowser(),
|
|
|
|
|
BrowserVersion: s.GetMajorVersion(),
|
|
|
|
|
Platform: s.GetOS(),
|
|
|
|
|
IsMobile: s.IsMobile(),
|
|
|
|
|
IsTablet: s.IsTablet(),
|
|
|
|
|
IsDesktop: s.IsDesktop(),
|
|
|
|
|
IsBot: s.IsBot(),
|
|
|
|
|
IsTV: s.IsTV(),
|
2024-12-06 21:31:20 -05:00
|
|
|
}
|
|
|
|
|
if err := s.db.Create(&sess).Error; err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
s.sess = &sess
|
2024-12-05 20:36:58 -05:00
|
|
|
return nil
|
|
|
|
|
}
|
2024-12-06 21:31:20 -05:00
|
|
|
|
|
|
|
|
func (s *HTTPContext) getOrCreateSessionID() string {
|
|
|
|
|
if ok := common.CookieExists(s.Context, common.SessionID); !ok {
|
|
|
|
|
sessionID := ksuid.New().String()
|
|
|
|
|
common.WriteCookie(s.Context, common.SessionID, sessionID)
|
|
|
|
|
return sessionID
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
sessionID, err := common.ReadCookie(s.Context, common.SessionID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
sessionID = ksuid.New().String()
|
|
|
|
|
common.WriteCookie(s.Context, common.SessionID, sessionID)
|
|
|
|
|
}
|
|
|
|
|
return sessionID
|
|
|
|
|
}
|