You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

discovery_cache.go 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package openid
  5. import (
  6. "sync"
  7. "time"
  8. "github.com/yohcop/openid-go"
  9. )
  10. type timedDiscoveredInfo struct {
  11. info openid.DiscoveredInfo
  12. time time.Time
  13. }
  14. type timedDiscoveryCache struct {
  15. cache map[string]timedDiscoveredInfo
  16. ttl time.Duration
  17. mutex *sync.Mutex
  18. }
  19. func newTimedDiscoveryCache(ttl time.Duration) *timedDiscoveryCache {
  20. return &timedDiscoveryCache{cache: map[string]timedDiscoveredInfo{}, ttl: ttl, mutex: &sync.Mutex{}}
  21. }
  22. func (s *timedDiscoveryCache) Put(id string, info openid.DiscoveredInfo) {
  23. s.mutex.Lock()
  24. defer s.mutex.Unlock()
  25. s.cache[id] = timedDiscoveredInfo{info: info, time: time.Now()}
  26. }
  27. // Delete timed-out cache entries
  28. func (s *timedDiscoveryCache) cleanTimedOut() {
  29. now := time.Now()
  30. for k, e := range s.cache {
  31. diff := now.Sub(e.time)
  32. if diff > s.ttl {
  33. delete(s.cache, k)
  34. }
  35. }
  36. }
  37. func (s *timedDiscoveryCache) Get(id string) openid.DiscoveredInfo {
  38. s.mutex.Lock()
  39. defer s.mutex.Unlock()
  40. // Delete old cached while we are at it.
  41. s.cleanTimedOut()
  42. if info, has := s.cache[id]; has {
  43. return info.info
  44. }
  45. return nil
  46. }