Skip to content

Commit

Permalink
Sync
Browse files Browse the repository at this point in the history
  • Loading branch information
mbilski committed Aug 16, 2023
1 parent 1210e97 commit 5cac234
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
31 changes: 31 additions & 0 deletions oauth2.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"net/url"
"strings"
"sync"
"time"

"golang.org/x/oauth2/advancedauth"
"golang.org/x/oauth2/internal"
Expand Down Expand Up @@ -316,6 +317,8 @@ type reuseTokenSource struct {

mu sync.Mutex // guards t
t *Token

expiryDelta time.Duration
}

// Token returns the current token if it's still valid, else will
Expand All @@ -331,6 +334,7 @@ func (s *reuseTokenSource) Token() (*Token, error) {
if err != nil {
return nil, err
}
t.expiryDelta = s.expiryDelta
s.t = t
return t, nil
}
Expand Down Expand Up @@ -405,3 +409,30 @@ func ReuseTokenSource(t *Token, src TokenSource) TokenSource {
new: src,
}
}

// ReuseTokenSource returns a TokenSource that acts in the same manner as the
// TokenSource returned by ReuseTokenSource, except the expiry buffer is
// configurable. The expiration time of a token is calculated as
// t.Expiry.Add(-earlyExpiry).
func ReuseTokenSourceWithExpiry(t *Token, src TokenSource, earlyExpiry time.Duration) TokenSource {
// Don't wrap a reuseTokenSource in itself. That would work,
// but cause an unnecessary number of mutex operations.
// Just build the equivalent one.
if rt, ok := src.(*reuseTokenSource); ok {
if t == nil {
// Just use it directly, but set the expiryDelta to earlyExpiry,
// so the behavior matches what the user expects.
rt.expiryDelta = earlyExpiry
return rt
}
src = rt.new
}
if t != nil {
t.expiryDelta = earlyExpiry
}
return &reuseTokenSource{
t: t,
new: src,
expiryDelta: earlyExpiry,
}
}
10 changes: 10 additions & 0 deletions token.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ import (
// expirations due to client-server time mismatches.
const expiryDelta = 10 * time.Second

// defaultExpiryDelta determines how earlier a token should be considered
// expired than its actual expiration time. It is used to avoid late
// expirations due to client-server time mismatches.
const defaultExpiryDelta = 10 * time.Second

// Token represents the credentials used to authorize
// the requests to access protected resources on the OAuth 2.0
// provider's backend.
Expand Down Expand Up @@ -52,6 +57,11 @@ type Token struct {
// raw optionally contains extra metadata from the server
// when updating a token.
raw interface{}

// expiryDelta is used to calculate when a token is considered
// expired, by subtracting from Expiry. If zero, defaultExpiryDelta
// is used.
expiryDelta time.Duration
}

// Type returns t.TokenType if non-empty, else "Bearer".
Expand Down

0 comments on commit 5cac234

Please sign in to comment.