github.com/orange-cloudfoundry/cli@v7.1.0+incompatible/api/uaa/noaabridge/token_refresher.go (about)

     1  // Package noaabridge wraps a UAA client and a tokenCache to support the
     2  // TokenRefresher interface for noaa/consumer.
     3  package noaabridge
     4  
     5  import "code.cloudfoundry.org/cli/api/uaa"
     6  
     7  //go:generate counterfeiter . UAAClient
     8  
     9  // UAAClient is the interface for getting a valid access token
    10  type UAAClient interface {
    11  	RefreshAccessToken(refreshToken string) (uaa.RefreshedTokens, error)
    12  }
    13  
    14  //go:generate counterfeiter . TokenCache
    15  
    16  // TokenCache is where the UAA token information is stored.
    17  type TokenCache interface {
    18  	RefreshToken() string
    19  	SetAccessToken(token string)
    20  	SetRefreshToken(token string)
    21  }
    22  
    23  // TokenRefresher implements the TokenRefresher interface. It requires a UAA
    24  // client and a token cache for storing the access and refresh tokens.
    25  type TokenRefresher struct {
    26  	uaaClient UAAClient
    27  	cache     TokenCache
    28  }
    29  
    30  // NewTokenRefresher returns back a pointer to a TokenRefresher.
    31  func NewTokenRefresher(uaaClient UAAClient, cache TokenCache) *TokenRefresher {
    32  	return &TokenRefresher{
    33  		uaaClient: uaaClient,
    34  		cache:     cache,
    35  	}
    36  }
    37  
    38  // RefreshAuthToken refreshes the current Authorization Token and stores the
    39  // Access and Refresh token in it's cache. The returned Authorization Token
    40  // includes the type prefixed by a space.
    41  func (t *TokenRefresher) RefreshAuthToken() (string, error) {
    42  	tokens, err := t.uaaClient.RefreshAccessToken(t.cache.RefreshToken())
    43  	if err != nil {
    44  		return "", err
    45  	}
    46  
    47  	t.cache.SetAccessToken(tokens.AuthorizationToken())
    48  	t.cache.SetRefreshToken(tokens.RefreshToken)
    49  	return tokens.AuthorizationToken(), nil
    50  }