2014-09-05 12:47:20 -04:00
|
|
|
package googlecompute
|
|
|
|
|
|
|
|
import (
|
2015-10-08 00:36:31 -04:00
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
2014-09-05 12:47:20 -04:00
|
|
|
"os"
|
|
|
|
|
2019-07-02 19:16:13 -04:00
|
|
|
"golang.org/x/oauth2/google"
|
|
|
|
"golang.org/x/oauth2/jwt"
|
|
|
|
)
|
2015-10-08 00:36:31 -04:00
|
|
|
|
2020-09-20 10:18:37 -04:00
|
|
|
type ServiceAccount struct {
|
|
|
|
jsonKey []byte
|
|
|
|
jwt *jwt.Config
|
|
|
|
}
|
|
|
|
|
2020-10-01 15:39:06 -04:00
|
|
|
// ProcessAccountFile will return a ServiceAccount for the JSON account file stored in text.
|
|
|
|
// Otherwise it will return an error if text does not look or reference a valid account file.
|
2020-09-20 10:18:37 -04:00
|
|
|
func ProcessAccountFile(text string) (*ServiceAccount, error) {
|
2015-10-08 00:36:31 -04:00
|
|
|
// Assume text is a JSON string
|
2020-10-01 15:39:06 -04:00
|
|
|
if conf, err := google.JWTConfigFromJSON([]byte(text), DriverScopes...); err == nil {
|
|
|
|
return &ServiceAccount{
|
|
|
|
jsonKey: []byte(text),
|
|
|
|
jwt: conf,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// If text was not JSON, assume it is a file path instead
|
|
|
|
if _, err := os.Stat(text); os.IsNotExist(err) {
|
|
|
|
return nil, fmt.Errorf("account_file path does not exist: %s", text)
|
|
|
|
}
|
|
|
|
|
|
|
|
data, err := ioutil.ReadFile(text)
|
2019-07-02 19:16:13 -04:00
|
|
|
if err != nil {
|
2020-10-01 15:39:06 -04:00
|
|
|
return nil, fmt.Errorf("Error reading account_file from path '%s': %s", text, err)
|
2014-09-05 12:47:20 -04:00
|
|
|
}
|
2020-10-01 15:39:06 -04:00
|
|
|
|
|
|
|
conf, err := google.JWTConfigFromJSON(data, DriverScopes...)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Error parsing account_file: %s", err)
|
|
|
|
}
|
|
|
|
|
2020-09-20 10:18:37 -04:00
|
|
|
return &ServiceAccount{
|
|
|
|
jsonKey: data,
|
|
|
|
jwt: conf,
|
|
|
|
}, nil
|
2014-09-05 12:47:20 -04:00
|
|
|
}
|