2020-06-25 01:20:58 +02:00
|
|
|
package session
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io/ioutil"
|
|
|
|
"path"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
gc "github.com/patrickmn/go-cache"
|
|
|
|
"github.com/photoprism/photoprism/internal/entity"
|
|
|
|
)
|
|
|
|
|
|
|
|
// New returns a new session store with an optional cachePath.
|
|
|
|
func New(expiration time.Duration, cachePath string) *Session {
|
|
|
|
s := &Session{}
|
|
|
|
|
|
|
|
cleanupInterval := 15 * time.Minute
|
|
|
|
|
|
|
|
if cachePath != "" {
|
|
|
|
var savedItems map[string]Saved
|
|
|
|
|
|
|
|
items := make(map[string]gc.Item)
|
|
|
|
s.cacheFile = path.Join(cachePath, "sessions.json")
|
|
|
|
|
|
|
|
if cached, err := ioutil.ReadFile(s.cacheFile); err != nil {
|
|
|
|
log.Infof("session: %s", err)
|
|
|
|
} else if err := json.Unmarshal(cached, &savedItems); err != nil {
|
|
|
|
log.Errorf("session: %s", err)
|
|
|
|
} else {
|
|
|
|
for key, saved := range savedItems {
|
2020-06-25 14:54:04 +02:00
|
|
|
user := entity.FindPersonByUID(saved.User)
|
2020-06-25 01:20:58 +02:00
|
|
|
|
|
|
|
if user == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
var tokens []string
|
|
|
|
var shared []string
|
|
|
|
|
|
|
|
for _, token := range saved.Tokens {
|
|
|
|
links := entity.FindLinks(token, "")
|
|
|
|
|
|
|
|
if len(links) > 0 {
|
|
|
|
for _, link := range links {
|
|
|
|
shared = append(shared, link.LinkUID)
|
|
|
|
}
|
|
|
|
tokens = append(tokens, token)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2020-06-25 14:54:04 +02:00
|
|
|
data := Data{User: *user, Tokens: tokens, Shares: shared}
|
2020-06-25 01:20:58 +02:00
|
|
|
items[key] = gc.Item{Expiration: saved.Expiration, Object: data}
|
|
|
|
}
|
|
|
|
|
|
|
|
s.cache = gc.NewFrom(expiration, cleanupInterval, items)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.cache == nil {
|
|
|
|
s.cache = gc.New(expiration, cleanupInterval)
|
|
|
|
}
|
|
|
|
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Session) Save() error {
|
|
|
|
if s.cacheFile == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
items := s.cache.Items()
|
|
|
|
savedItems := make(map[string]Saved, len(items))
|
|
|
|
|
|
|
|
for key, item := range items {
|
2020-06-25 14:54:04 +02:00
|
|
|
saved := item.Object.(Data).Saved()
|
2020-06-25 01:20:58 +02:00
|
|
|
saved.Expiration = item.Expiration
|
|
|
|
savedItems[key] = saved
|
|
|
|
}
|
|
|
|
|
|
|
|
if serialized, err := json.MarshalIndent(savedItems, "", " "); err != nil {
|
|
|
|
return err
|
|
|
|
} else if err = ioutil.WriteFile(s.cacheFile, serialized, 0600); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|