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.1KB

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