go-twitch/auth/token_source.go

39 lines
554 B
Go
Raw Permalink Normal View History

2024-03-04 18:14:38 -05:00
package auth
import (
"sync"
"golang.org/x/oauth2"
)
type TokenSource struct {
client *Client
token *Token
mu sync.Mutex
}
func (c *Client) TokenSource(token *Token) oauth2.TokenSource {
return &TokenSource{
client: c,
token: token,
}
}
func (ts *TokenSource) Token() (*oauth2.Token, error) {
ts.mu.Lock()
defer ts.mu.Unlock()
if ts.token.Valid() {
return ts.token.Underlying(), nil
}
token, err := ts.client.RefreshToken(ts.token)
if err != nil {
return nil, err
}
ts.token = token
return ts.token.Underlying(), nil
}