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