Skip to content

Commit

Permalink
Add Transport.Expiry() to query token expiration
Browse files Browse the repository at this point in the history
Since it could be interesting in some cases, return this for the user
to examine.

Also factor out the "is a token expired" logic and return the current
value of "we think it's expired" when calling Expiry().

    expiresAt, expired, err := trans.Expiry()
  • Loading branch information
wade-arista authored and wlynch committed Jan 24, 2023
1 parent 8f41e65 commit 0d537b3
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
Expand Down Expand Up @@ -136,12 +137,16 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
return resp, err
}

func (at *accessToken) isExpired() bool {
return at == nil || at.ExpiresAt.Add(-time.Minute).Before(time.Now())
}

// Token checks the active token expiration and renews if necessary. Token returns
// a valid access token. If renewal fails an error is returned.
func (t *Transport) Token(ctx context.Context) (string, error) {
t.mu.Lock()
defer t.mu.Unlock()
if t.token == nil || t.token.ExpiresAt.Add(-time.Minute).Before(time.Now()) {
if t.token.isExpired() {
// Token is not set or expired/nearly expired, so refresh
if err := t.refreshToken(ctx); err != nil {
return "", fmt.Errorf("could not refresh installation id %v's token: %w", t.installationID, err)
Expand All @@ -167,6 +172,14 @@ func (t *Transport) Repositories() ([]github.Repository, error) {
return t.token.Repositories, nil
}

// Expiry returns a transport token's expiration time and current expiration status.
func (t *Transport) Expiry() (expiresAt time.Time, expired bool, err error) {
if t.token == nil {
return time.Time{}, true, errors.New("Expiry() = unknown, err: nil token")
}
return t.token.ExpiresAt, t.token.isExpired(), nil
}

func (t *Transport) refreshToken(ctx context.Context) error {
// Convert InstallationTokenOptions into a ReadWriter to pass as an argument to http.NewRequest.
body, err := GetReadWriter(t.InstallationTokenOptions)
Expand Down

0 comments on commit 0d537b3

Please sign in to comment.