Files
sonr/internal/gateway/context/context.go
T

51 lines
1.3 KiB
Go
Raw Normal View History

package context
2024-12-05 20:36:58 -05:00
import (
"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
)
// 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
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
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
}