go-twitch/auth/token_source.go

40 lines
583 B
Go
Raw Permalink 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 *Auth
2024-03-04 18:14:38 -05:00
token *Token
mu sync.Mutex
}
func (c *Auth) TokenSource(token *Token) oauth2.TokenSource {
2024-03-04 18:14:38 -05:00
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
}