github.com/clerkinc/clerk-sdk-go@v1.49.1/clerk/jwks_cache.go (about)

     1  package clerk
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  	"time"
     7  
     8  	"github.com/go-jose/go-jose/v3"
     9  )
    10  
    11  type jwksCache struct {
    12  	sync.RWMutex
    13  	jwks      *JWKS
    14  	expiresAt time.Time
    15  }
    16  
    17  func (c *jwksCache) isInvalid() bool {
    18  	c.RLock()
    19  	defer c.RUnlock()
    20  
    21  	return c.jwks == nil || len(c.jwks.Keys) == 0 || time.Now().After(c.expiresAt)
    22  }
    23  
    24  func (c *jwksCache) set(jwks *JWKS) {
    25  	c.Lock()
    26  	defer c.Unlock()
    27  
    28  	c.jwks = jwks
    29  	c.expiresAt = time.Now().Add(time.Hour)
    30  }
    31  
    32  func (c *jwksCache) get(kid string) (*jose.JSONWebKey, error) {
    33  	c.RLock()
    34  	defer c.RUnlock()
    35  
    36  	for _, key := range c.jwks.Keys {
    37  		if key.KeyID == kid {
    38  			return &key, nil
    39  		}
    40  	}
    41  
    42  	return nil, fmt.Errorf("no jwk key found for kid %s", kid)
    43  }