token.go raw

   1  package token
   2  
   3  import (
   4  	"context"
   5  	"fmt"
   6  
   7  	"golang.org/x/oauth2"
   8  )
   9  
  10  const tokenURL = "authorization/token"
  11  
  12  type TokenSource struct {
  13  	BaseURL  string
  14  	Username string
  15  	Password string
  16  	T        *oauth2.Token
  17  }
  18  
  19  func (ts *TokenSource) Token() (*oauth2.Token, error) {
  20  	conf := &oauth2.Config{Endpoint: ts.getTokenEndpoint()}
  21  
  22  	if ts.T == nil {
  23  		return ts.PasswordCredentialsToken(conf)
  24  	}
  25  
  26  	token, err := conf.TokenSource(context.Background(), ts.T).Token()
  27  
  28  	if err != nil {
  29  		return ts.PasswordCredentialsToken(conf)
  30  	}
  31  
  32  	ts.T = token
  33  
  34  	return token, err
  35  }
  36  
  37  func (ts *TokenSource) PasswordCredentialsToken(conf *oauth2.Config) (token *oauth2.Token, err error) {
  38  	token, err = conf.PasswordCredentialsToken(context.Background(), ts.Username, ts.Password)
  39  	ts.T = token
  40  
  41  	return token, err
  42  }
  43  
  44  func (ts *TokenSource) getTokenEndpoint() oauth2.Endpoint {
  45  	return oauth2.Endpoint{TokenURL: getTokenURL(ts.BaseURL)}
  46  }
  47  
  48  func getTokenURL(baseURL string) string {
  49  	return fmt.Sprintf("%s/%s", baseURL, tokenURL)
  50  }
  51