diff --git a/pkg/auth/authenticator.go b/pkg/auth/authenticator.go index 62164f4..f87669a 100644 --- a/pkg/auth/authenticator.go +++ b/pkg/auth/authenticator.go @@ -50,7 +50,7 @@ func (a *Authenticator) Provider(name string) AuthProvider { func (a *Authenticator) InitAuth(s storage.Store) error { a.Flows = make(FlowStore) - a.Sessions = make(SessionStore) + a.Sessions.init() hap, err := NewHAProvider(s) if err != nil { return err diff --git a/pkg/auth/session.go b/pkg/auth/session.go new file mode 100644 index 0000000..d0f89cb --- /dev/null +++ b/pkg/auth/session.go @@ -0,0 +1,55 @@ +package auth + +import ( + "net/http" + "time" +) + +type SessionStore struct { + s map[TokenID]*Token + lastCull time.Time +} + +type TokenID string + +type Token struct { + ID TokenID + Ctime time.Time + Expires time.Duration + Addr string +} + +func (ss *SessionStore) init() { + ss.s = make(map[TokenID]*Token) +} + +const cullInterval = 5 * time.Minute + +func (ss *SessionStore) cull() { + if now := time.Now(); now.Sub(ss.lastCull) > cullInterval { + for k, v := range ss.s { + if now.After(v.Ctime.Add(v.Expires)) { + delete(ss.s, k) + } + } + } +} + +func (ss *SessionStore) register(t *Token) { + ss.cull() + ss.s[t.ID] = t +} + +func (a *Authenticator) NewToken(r *http.Request, f *Flow) TokenID { + id := TokenID(genUUID()) + + t := &Token{ + ID: id, + Ctime: time.Now(), + Addr: r.RemoteAddr, + } + + a.Sessions.register(t) + + return id +}