2019-11-12 23:41:42 +00:00
|
|
|
package azure
|
2018-05-28 14:40:33 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2019-03-21 01:20:14 +00:00
|
|
|
"github.com/portainer/portainer/api"
|
|
|
|
"github.com/portainer/portainer/api/http/client"
|
2018-05-28 14:40:33 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
azureAPIToken struct {
|
|
|
|
value string
|
|
|
|
expirationTime time.Time
|
|
|
|
}
|
|
|
|
|
2019-11-12 23:41:42 +00:00
|
|
|
Transport struct {
|
2018-05-28 14:40:33 +00:00
|
|
|
credentials *portainer.AzureCredentials
|
|
|
|
client *client.HTTPClient
|
|
|
|
token *azureAPIToken
|
|
|
|
mutex sync.Mutex
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2019-11-12 23:41:42 +00:00
|
|
|
// NewTransport returns a pointer to a new instance of Transport that implements the HTTP Transport
|
|
|
|
// interface for proxying requests to the Azure API.
|
|
|
|
func NewTransport(credentials *portainer.AzureCredentials) *Transport {
|
|
|
|
return &Transport{
|
2018-05-28 14:40:33 +00:00
|
|
|
credentials: credentials,
|
|
|
|
client: client.NewHTTPClient(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-13 00:12:55 +00:00
|
|
|
// RoundTrip is the implementation of the the http.RoundTripper interface
|
2019-11-12 23:41:42 +00:00
|
|
|
func (transport *Transport) RoundTrip(request *http.Request) (*http.Response, error) {
|
|
|
|
err := transport.retrieveAuthenticationToken()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
request.Header.Set("Authorization", "Bearer "+transport.token.value)
|
|
|
|
return http.DefaultTransport.RoundTrip(request)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (transport *Transport) authenticate() error {
|
2018-05-28 14:40:33 +00:00
|
|
|
token, err := transport.client.ExecuteAzureAuthenticationRequest(transport.credentials)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
expiresOn, err := strconv.ParseInt(token.ExpiresOn, 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
transport.token = &azureAPIToken{
|
|
|
|
value: token.AccessToken,
|
|
|
|
expirationTime: time.Unix(expiresOn, 0),
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-11-12 23:41:42 +00:00
|
|
|
func (transport *Transport) retrieveAuthenticationToken() error {
|
2018-05-28 14:40:33 +00:00
|
|
|
transport.mutex.Lock()
|
|
|
|
defer transport.mutex.Unlock()
|
|
|
|
|
|
|
|
if transport.token == nil {
|
|
|
|
return transport.authenticate()
|
|
|
|
}
|
|
|
|
|
|
|
|
timeLimit := time.Now().Add(-5 * time.Minute)
|
|
|
|
if timeLimit.After(transport.token.expirationTime) {
|
|
|
|
return transport.authenticate()
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|