go-twitch/auth/token_source.go

40 lines
583 B
Go

package auth
import (
"context"
"sync"
"golang.org/x/oauth2"
)
type TokenSource struct {
client *Auth
token *Token
mu sync.Mutex
}
func (c *Auth) 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(context.Background(), ts.token)
if err != nil {
return nil, err
}
ts.token = token
return ts.token.Underlying(), nil
}