mirror of
https://github.com/cf-sonr/motr.git
synced 2026-01-12 02:59:13 +00:00
73 lines
1.7 KiB
Go
73 lines
1.7 KiB
Go
//go:build js && wasm
|
|
// +build js,wasm
|
|
|
|
package session
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/segmentio/ksuid"
|
|
"github.com/sonr-io/motr/middleware/kvstore"
|
|
"github.com/sonr-io/motr/pkg/cookies"
|
|
)
|
|
|
|
const kDefaultSessionTTL = 1 * time.Hour
|
|
|
|
func DetermineID(c echo.Context) string {
|
|
if ok := cookies.SessionID.Exists(c); ok {
|
|
c.Echo().Logger.Debug("Has session ID in cookie")
|
|
if checkSessionTTL(c) {
|
|
sessionID, err := cookies.SessionID.Read(c)
|
|
if err != nil {
|
|
sessionID = initNewID(c)
|
|
}
|
|
return sessionID
|
|
}
|
|
c.Echo().Logger.Debug("Session TTL expired, writing new session ID to cookie")
|
|
cookies.SessionID.Write(c, initNewID(c))
|
|
return getIDFromCookie(c)
|
|
}
|
|
c.Echo().Logger.Debug("Has session ID in cookie")
|
|
sessionID, err := cookies.SessionID.Read(c)
|
|
if err != nil {
|
|
sessionID = initNewID(c)
|
|
}
|
|
return sessionID
|
|
}
|
|
|
|
func initNewID(c echo.Context) string {
|
|
id := ksuid.New().String()
|
|
cookies.SessionID.Write(c, id)
|
|
ttl := time.Now().Add(kDefaultSessionTTL)
|
|
kvstore.Sessions().SetInt(id, int(ttl.Unix()))
|
|
c.Echo().Logger.Debug("Wrote new session ID to cookie")
|
|
return id
|
|
}
|
|
|
|
func checkSessionTTL(c echo.Context) bool {
|
|
ttl := getSessionTTL(c)
|
|
if ttl < int(time.Now().Unix()) {
|
|
c.Echo().Logger.Debug("Session TTL expired")
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func getIDFromCookie(c echo.Context) string {
|
|
sessionID, err := cookies.SessionID.Read(c)
|
|
if err != nil {
|
|
sessionID = initNewID(c)
|
|
}
|
|
return sessionID
|
|
}
|
|
|
|
func getSessionTTL(c echo.Context) int {
|
|
ttl, err := kvstore.Sessions().GetInt(getIDFromCookie(c))
|
|
if err != nil {
|
|
ttl = int(time.Now().Add(kDefaultSessionTTL).Unix())
|
|
kvstore.Sessions().SetInt(getIDFromCookie(c), ttl)
|
|
}
|
|
return ttl
|
|
}
|