2019-12-28 09:48:36 +01:00
|
|
|
package session
|
|
|
|
|
|
|
|
import (
|
2020-04-20 13:50:28 +02:00
|
|
|
"encoding/json"
|
|
|
|
"io/ioutil"
|
2019-12-28 09:48:36 +01:00
|
|
|
|
|
|
|
gc "github.com/patrickmn/go-cache"
|
|
|
|
)
|
|
|
|
|
2020-04-20 13:50:28 +02:00
|
|
|
func (s *Session) Create(data interface{}) string {
|
2019-12-28 09:48:36 +01:00
|
|
|
token := Token()
|
2020-04-20 13:50:28 +02:00
|
|
|
s.cache.Set(token, data, gc.DefaultExpiration)
|
2019-12-28 09:48:36 +01:00
|
|
|
log.Debugf("session: created")
|
2020-04-20 13:50:28 +02:00
|
|
|
|
|
|
|
if err := s.Save(); err != nil {
|
|
|
|
log.Errorf("session: %s", err)
|
|
|
|
}
|
|
|
|
|
2019-12-28 09:48:36 +01:00
|
|
|
return token
|
|
|
|
}
|
|
|
|
|
2020-04-20 13:50:28 +02:00
|
|
|
func (s *Session) Delete(token string) {
|
|
|
|
s.cache.Delete(token)
|
2019-12-28 09:48:36 +01:00
|
|
|
log.Debugf("session: deleted")
|
2020-04-20 13:50:28 +02:00
|
|
|
|
|
|
|
if err := s.Save(); err != nil {
|
|
|
|
log.Errorf("session: %s", err)
|
|
|
|
}
|
2019-12-28 09:48:36 +01:00
|
|
|
}
|
|
|
|
|
2020-04-20 13:50:28 +02:00
|
|
|
func (s *Session) Get(token string) (data interface{}, exists bool) {
|
|
|
|
return s.cache.Get(token)
|
2019-12-28 09:48:36 +01:00
|
|
|
}
|
|
|
|
|
2020-04-20 13:50:28 +02:00
|
|
|
func (s *Session) Exists(token string) bool {
|
|
|
|
_, found := s.cache.Get(token)
|
2019-12-28 09:48:36 +01:00
|
|
|
|
|
|
|
return found
|
|
|
|
}
|
2020-04-20 13:50:28 +02:00
|
|
|
|
|
|
|
func (s *Session) Save() error {
|
|
|
|
if s.cacheFile == "" {
|
|
|
|
return nil
|
|
|
|
} else if serialized, err := json.MarshalIndent(s.cache.Items(), "", " "); err != nil {
|
|
|
|
return err
|
|
|
|
} else if err = ioutil.WriteFile(s.cacheFile, serialized, 0600); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|