61 lines
1.3 KiB
Go
61 lines
1.3 KiB
Go
package forwardauth
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/StiviiK/keycloak-traefik-forward-auth/pkg/options"
|
|
"github.com/google/uuid"
|
|
"github.com/pzentenoe/go-cache"
|
|
)
|
|
|
|
type SessionCache struct {
|
|
internal *cache.Cache
|
|
longLived bool
|
|
}
|
|
|
|
type SessionCacheItem struct {
|
|
IDToken string
|
|
RefreshToken string
|
|
}
|
|
|
|
func newSessionCache(options *options.Options) SessionCache {
|
|
longLived := options.SessionLifetime > 0
|
|
var nd int
|
|
if longLived {
|
|
nd = options.SessionLifetime
|
|
} else {
|
|
nd = 12
|
|
}
|
|
|
|
return SessionCache{
|
|
internal: cache.New(time.Hour*time.Duration(nd), time.Hour),
|
|
longLived: longLived,
|
|
}
|
|
}
|
|
|
|
func (c *SessionCache) Get(sessionId string) *SessionCacheItem {
|
|
itm, _ := c.internal.Get(sessionId)
|
|
if itm == nil {
|
|
return nil
|
|
}
|
|
return itm.(*SessionCacheItem)
|
|
}
|
|
|
|
func (c *SessionCache) Create(session *SessionCacheItem) string {
|
|
sessionId := uuid.New().String()
|
|
c.internal.SetDefault(sessionId, session)
|
|
return sessionId
|
|
}
|
|
|
|
func (c *SessionCache) Update(sessionId string, session *SessionCacheItem) {
|
|
_, exp, found := c.internal.GetWithExpiration(sessionId)
|
|
if found && c.longLived {
|
|
c.internal.Set(sessionId, session, exp.Sub(time.Now()))
|
|
} else {
|
|
c.internal.SetDefault(sessionId, session)
|
|
}
|
|
}
|
|
|
|
func (c *SessionCache) Delete(sessionId string) {
|
|
c.internal.Delete(sessionId)
|
|
}
|