go-twitch/auth/token_source.go

40 lines
587 B
Go
Raw Normal View History

2024-03-04 18:14:38 -05:00
package auth
import (
2024-03-08 13:05:54 -05:00
"context"
2024-03-04 18:14:38 -05:00
"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
}
2024-03-08 13:05:54 -05:00
token, err := ts.client.RefreshToken(context.Background(), ts.token)
2024-03-04 18:14:38 -05:00
if err != nil {
return nil, err
}
ts.token = token
return ts.token.Underlying(), nil
}