func main() {
	data, err := ioutil.ReadFile(key)
	if err != nil {
		log.Fatal(err)
	}

	conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/plus.profile.emails.read")
	if err != nil {
		log.Fatal(err)
	}

	client := conf.Client(oauth2.NoContext)
	plusService, err := plus.New(client)
	if err != nil {
		log.Fatal(err)
	}

	peopleService := plus.NewPeopleService(plusService)
	call := peopleService.Get("105303214497629424637")
	person, err := call.Do()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(person)
}
示例#2
0
func getCloudContext(aeCtx context.Context) (context.Context, error) {
	data, err := ioutil.ReadFile("gcs.xxjson")
	if err != nil {
		return nil, err
	}

	conf, err := google.JWTConfigFromJSON(
		data,
		storage.ScopeFullControl,
	)
	if err != nil {
		return nil, err
	}

	tokenSource := conf.TokenSource(aeCtx)

	hc := &http.Client{
		Transport: &oauth2.Transport{
			Source: tokenSource,
			Base:   &urlfetch.Transport{Context: aeCtx},
		},
	}

	return cloud.NewContext(appengine.AppID(aeCtx), hc), nil
}
func NewSalesforceOpportunityEventService(ctx context.Context, jsonPath, projectID, namespace string) (SalesforceOpportunityEventService, error) {

	logger.Infof("NewSalesforceOpportunityEventService: jsonPath - %s", jsonPath)
	jsonKey, err := ioutil.ReadFile(jsonPath)
	if err != nil {
		return nil, err
	}
	conf, err := google.JWTConfigFromJSON(
		jsonKey,
		pubsub.ScopeCloudPlatform,
		pubsub.ScopePubSub,
	)
	if err != nil {
		return nil, err
	}

	pubSubEvents := &SalesforceOpportunityEvents{
		conf:         conf,
		projectID:    projectID,
		Topic:        "opportunity_chages",
		Subscription: "opportunity_chages_sub" + namespace,
	}

	return pubSubEvents, nil
}
示例#4
0
func (s *shard) createOutputFile(c context.Context) (io.WriteCloser, error) {
	c, _ = context.WithTimeout(c, time.Duration(10)*time.Minute)
	// for development we can't use the appengine default credentials so
	// instead need to create our own oauth token source to access storage

	// TODO: maybe give job a chance to generate this - it could also
	// create the writer (?). The only reason we're doing it is to prevent
	// duplication and also handle the file rollup operations
	var client *cstorage.Client
	if appengine.IsDevAppServer() {
		jsonKey, err := ioutil.ReadFile("service-account.json")
		if err != nil {
			return nil, err
		}
		conf, err := google.JWTConfigFromJSON(jsonKey, cstorage.ScopeReadWrite)
		if err != nil {
			return nil, err
		}
		client, err = cstorage.NewClient(c, option.WithTokenSource(conf.TokenSource(c)))
		if err != nil {
			return nil, err
		}
	} else {
		var err error
		client, err = cstorage.NewClient(c)
		if err != nil {
			return nil, err
		}
	}

	o := client.Bucket(s.job.Bucket).Object(s.sliceFilename(s.Sequence)).NewWriter(c)

	// TODO: wrap writer to count bytes and continue slice if we get close to 10Mb limit (?)
	return o, nil
}
示例#5
0
文件: gce.go 项目: ltouati/rexray
func (d *driver) Init(r *core.RexRay) error {
	d.r = r

	var err error

	d.zone = d.r.Config.GetString("gce.zone")
	d.project = d.r.Config.GetString("gce.project")
	serviceAccountJSON, err := ioutil.ReadFile(d.r.Config.GetString("gce.keyfile"))
	if err != nil {
		log.WithField("provider", providerName).Fatalf("Could not read service account credentials file, %s => {%s}", d.r.Config.GetString("gce.keyfile"), err)
		return err
	}

	config, err := google.JWTConfigFromJSON(serviceAccountJSON,
		compute.ComputeScope,
	)
	client, err := compute.New(config.Client(context.Background()))

	if err != nil {
		log.WithField("provider", providerName).Fatalf("Could not create compute client => {%s}", err)
		return err
	}
	d.client = client
	instanceId, err := getCurrentInstanceId()
	if err != nil {
		log.WithField("provider", providerName).Fatalf("Could not get current  instance => {%s}", err)
		return err
	}
	d.currentInstanceId = instanceId
	log.WithField("provider", providerName).Info("storage driver initialized")
	return nil
}
示例#6
0
func Example_serviceAccount() {
	// Warning: The better way to use service accounts is to set GOOGLE_APPLICATION_CREDENTIALS
	// and use the Application Default Credentials.
	ctx := context.Background()
	// Use a JSON key file associated with a Google service account to
	// authenticate and authorize.
	// Go to https://console.developers.google.com/permissions/serviceaccounts to create
	// and download a service account key for your project.
	//
	// Note: The example uses the datastore client, but the same steps apply to
	// the other client libraries underneath this package.
	key, err := ioutil.ReadFile("/path/to/service-account-key.json")
	if err != nil {
		// TODO: handle error.
	}
	cfg, err := google.JWTConfigFromJSON(key, datastore.ScopeDatastore)
	if err != nil {
		// TODO: handle error.
	}
	client, err := datastore.NewClient(
		ctx, "project-id", option.WithTokenSource(cfg.TokenSource(ctx)))
	if err != nil {
		// TODO: handle error.
	}
	// Use the client.
	_ = client
}
示例#7
0
func (this *Factory) NewGCSImageStore(conf map[string]string) ImageStore {
	jsonKey, err := ioutil.ReadFile(conf["KeyFile"])
	if err != nil {
		log.Fatal(err)
	}
	cloudConf, err := google.JWTConfigFromJSON(
		jsonKey,
		gcs.ScopeFullControl,
	)
	if err != nil {
		log.Fatal(err)
	}

	bucket := conf["BucketName"]

	ctx := gcloud.NewContext(conf["AppID"], cloudConf.Client(oauth2.NoContext))
	mapper := NewNamePathMapper(conf["NamePathRegex"], conf["NamePathMap"])

	return NewGCSImageStore(
		ctx,
		bucket,
		conf["StoreRoot"],
		mapper,
	)
}
示例#8
0
func newContext(projectID, jsonKey string) (context.Context, error) {
	if projectID == "" {
		return nil, errors.New("project id not provided")
	}

	if jsonKey == "" {
		return nil, errors.New("JSON key not provided")
	}

	key, err := ioutil.ReadFile(jsonKey)
	if err != nil {
		return nil, err
	}

	conf, err := google.JWTConfigFromJSON(
		key,
		pubsub.ScopeCloudPlatform,
		pubsub.ScopePubSub,
	)
	if err != nil {
		return nil, err
	}

	ctx := cloud.NewContext(projectID, conf.Client(oauth2.NoContext))
	return ctx, nil
}
// New creates a Client from the configuration.
func New(ctx context.Context, config *Config) (*Client, error) {
	conf := *config
	certs := &Certificates{URL: publicCertsURL}
	var widgetURL *url.URL
	if conf.WidgetURL != "" {
		var err error
		widgetURL, err = url.Parse(conf.WidgetURL)
		if err != nil {
			return nil, fmt.Errorf("invalid WidgetURL: %s", conf.WidgetURL)
		}
	}
	var jc *jwt.Config
	if config.GoogleAppCredentialsPath != "" {
		b, err := ioutil.ReadFile(config.GoogleAppCredentialsPath)
		if err != nil {
			return nil, fmt.Errorf("invalid GoogleAppCredentialsPath: %v", err)
		}
		jc, err = google.JWTConfigFromJSON(b, identitytoolkitScope)
		if err != nil {
			return nil, err
		}
	}
	api, err := newAPIClient(ctx, jc)
	if err != nil {
		return nil, err
	}
	conf.normalize()
	return &Client{
		config:    &conf,
		widgetURL: widgetURL,
		certs:     certs,
		api:       api,
		jc:        jc,
	}, nil
}
示例#10
0
// connect - opens a new connection to bigquery, reusing the token if possible or regenerating a new auth token if required
func (c *Client) connect() (*bigquery.Service, error) {
	if c.token != nil {
		if !c.token.Valid() && c.service != nil {
			return c.service, nil
		}
	}

	// generate auth token and create service object
	//authScope := bigquery.BigqueryScope
	pemKeyBytes, err := ioutil.ReadFile(c.pemPath)
	if err != nil {
		panic(err)
	}

	t, err := google.JWTConfigFromJSON(
		pemKeyBytes,
		"https://www.googleapis.com/auth/bigquery")
	//t := jwt.NewToken(c.accountEmailAddress, bigquery.BigqueryScope, pemKeyBytes)
	client := t.Client(oauth2.NoContext)

	service, err := bigquery.New(client)
	if err != nil {
		return nil, err
	}

	c.service = service
	return service, nil
}
示例#11
0
func Example_auth() {
	// Initialize an authorized context with Google Developers Console
	// JSON key. Read the google package examples to learn more about
	// different authorization flows you can use.
	// http://godoc.org/golang.org/x/oauth2/google
	jsonKey, err := ioutil.ReadFile("/path/to/json/keyfile.json")
	if err != nil {
		log.Fatal(err)
	}
	conf, err := google.JWTConfigFromJSON(
		jsonKey,
		storage.ScopeFullControl,
	)
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()
	client, err := storage.NewClient(ctx, cloud.WithTokenSource(conf.TokenSource(ctx)))
	if err != nil {
		log.Fatal(err)
	}

	// Use the client (see other examples)
	doSomething(client)

	// After using the client, free any resources (e.g. network connections).
	client.Close()
}
示例#12
0
// newClient creates http.Client with a jwt service account when
// jsonFile flag is specified, otherwise by obtaining the GCE service
// account's access token.
func newClient(jsonFile string) (*http.Client, error) {
	if jsonFile != "" {
		jsonKey, err := ioutil.ReadFile(jsonFile)
		if err != nil {
			return nil, err
		}
		conf, err := google.JWTConfigFromJSON(jsonKey, pubsub.ScopePubSub)
		if err != nil {
			return nil, err
		}
		return conf.Client(oauth2.NoContext), nil
	}
	if metadata.OnGCE() {
		c := &http.Client{
			Transport: &oauth2.Transport{
				Source: google.ComputeTokenSource(""),
			},
		}
		if *projID == "" {
			projectID, err := metadata.ProjectID()
			if err != nil {
				return nil, fmt.Errorf("ProjectID failed, %v", err)
			}
			*projID = projectID
		}
		return c, nil
	}
	return nil, errors.New("Could not create an authenticated client.")
}
示例#13
0
func init() {
	bucket := os.Getenv("REGISTRY_STORAGE_GCS_BUCKET")
	credentials := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")

	// Skip GCS storage driver tests if environment variable parameters are not provided
	skipGCS = func() string {
		if bucket == "" || credentials == "" {
			return "The following environment variables must be set to enable these tests: REGISTRY_STORAGE_GCS_BUCKET, GOOGLE_APPLICATION_CREDENTIALS"
		}
		return ""
	}

	if skipGCS() != "" {
		return
	}

	root, err := ioutil.TempDir("", "driver-")
	if err != nil {
		panic(err)
	}
	defer os.Remove(root)
	var ts oauth2.TokenSource
	var email string
	var privateKey []byte

	ts, err = google.DefaultTokenSource(ctx.Background(), storage.ScopeFullControl)
	if err != nil {
		// Assume that the file contents are within the environment variable since it exists
		// but does not contain a valid file path
		jwtConfig, err := google.JWTConfigFromJSON([]byte(credentials), storage.ScopeFullControl)
		if err != nil {
			panic(fmt.Sprintf("Error reading JWT config : %s", err))
		}
		email = jwtConfig.Email
		privateKey = []byte(jwtConfig.PrivateKey)
		if len(privateKey) == 0 {
			panic("Error reading JWT config : missing private_key property")
		}
		if email == "" {
			panic("Error reading JWT config : missing client_email property")
		}
		ts = jwtConfig.TokenSource(ctx.Background())
	}

	gcsDriverConstructor = func(rootDirectory string) (storagedriver.StorageDriver, error) {
		parameters := driverParameters{
			bucket:        bucket,
			rootDirectory: root,
			email:         email,
			privateKey:    privateKey,
			client:        oauth2.NewClient(ctx.Background(), ts),
		}

		return New(parameters)
	}

	testsuites.RegisterSuite(func() (storagedriver.StorageDriver, error) {
		return gcsDriverConstructor(root)
	}, skipGCS)
}
示例#14
0
// Do handles command-line requests to the Google BrainMaps API
func (dtype *Type) Do(cmd datastore.Request, reply *datastore.Response) error {
	switch cmd.Argument(1) {
	case "volumes":
		// Read in the JSON Web Token
		jwtdata, err := ioutil.ReadFile(cmd.Argument(2))
		if err != nil {
			return fmt.Errorf("Cannot load JSON Web Token file (%s): %v", cmd.Argument(2), err)
		}
		conf, err := google.JWTConfigFromJSON(jwtdata, "https://www.googleapis.com/auth/brainmaps")
		if err != nil {
			return fmt.Errorf("Cannot establish JWT Config file from Google: %v", err)
		}
		client := conf.Client(oauth2.NoContext)

		// Make the call.
		url := fmt.Sprintf("%s/volumes", bmapsPrefix)
		resp, err := client.Get(url)
		if err != nil {
			return fmt.Errorf("Error getting volumes metadata from Google: %v", err)
		}
		if resp.StatusCode != http.StatusOK {
			return fmt.Errorf("Unexpected status code %d returned when getting volumes for user", resp.StatusCode)
		}
		metadata, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return err
		}
		resp.Body.Close()
		reply.Text = string(metadata)
		return nil

	default:
		return fmt.Errorf("unknown command for type %s", dtype.GetTypeName())
	}
}
示例#15
0
文件: main.go 项目: kkdai/Golang
func main() {
	// Your credentials should be obtained from the Google
	// Developer Console (https://console.developers.google.com).
	// Navigate to your project, then see the "Credentials" page
	// under "APIs & Auth".
	// To create a service account client, click "Create new Client ID",
	// select "Service Account", and click "Create Client ID". A JSON
	// key file will then be downloaded to your computer.
	data, err := ioutil.ReadFile("downloaded.json")
	if err != nil {
		log.Fatal(err)
	}
	conf, err := google.JWTConfigFromJSON(data, "https://www.google.com/m8/feeds")
	if err != nil {
		log.Fatal(err)
	}
	// Initiate an http.Client. The following GET request will be
	// authorized and authenticated on the behalf of
	// your service account.
	client := conf.Client(oauth2.NoContext)
	res, err := client.Get("https://www.google.com/m8/feeds/contacts/default/full")
	if err != nil {
		log.Println("err:", err)
	}
	body, err := ioutil.ReadAll(res.Body)
	log.Println(string(body))
}
示例#16
0
// TODO(djd): reevaluate this example given new Client config.
func Example_auth() *datastore.Client {
	// Initialize an authorized context with Google Developers Console
	// JSON key. Read the google package examples to learn more about
	// different authorization flows you can use.
	// http://godoc.org/golang.org/x/oauth2/google
	jsonKey, err := ioutil.ReadFile("/path/to/json/keyfile.json")
	if err != nil {
		log.Fatal(err)
	}
	conf, err := google.JWTConfigFromJSON(
		jsonKey,
		datastore.ScopeDatastore,
		datastore.ScopeUserEmail,
	)
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, "project-id", cloud.WithTokenSource(conf.TokenSource(ctx)))
	if err != nil {
		log.Fatal(err)
	}
	// Use the client (see other examples).
	return client
}
示例#17
0
// NewServiceAccountFromKey constructs the PerRPCCredentials using the JSON key slice
// from a Google Developers service account.
func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.PerRPCCredentials, error) {
	config, err := google.JWTConfigFromJSON(jsonKey, scope...)
	if err != nil {
		return nil, err
	}
	return serviceAccount{config: config}, nil
}
示例#18
0
func main() {
	log.SetFlags(0)
	plugin.Param("workspace", &workspace)
	plugin.Param("build", &build)
	plugin.Param("repo", &repo)
	plugin.Param("vargs", &vargs)
	plugin.MustParse()
	sort.Strings(vargs.Gzip) // need for matchGzip

	// context for all clients
	ctx := context.Background()
	// GitHub client
	gts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: vargs.GitHubToken})
	client.ghub = github.NewClient(oauth2.NewClient(ctx, gts))
	// GCS client
	auth, err := google.JWTConfigFromJSON([]byte(vargs.AuthKey), storage.ScopeFullControl)
	if err != nil {
		fatalf("auth: %v", err)
	}
	tsrc := auth.TokenSource(ctx)
	client.gcs, err = storage.NewClient(ctx, cloud.WithTokenSource(auth.TokenSource(ctx)))
	if err != nil {
		fatalf("storage client: %v", err)
	}
	// http client with service account authorization
	client.http = oauth2.NewClient(ctx, tsrc)

	run()
	if ecode != 0 {
		msg := fmt.Sprintf("exited with code %d", ecode)
		updateStatus("error", msg, stagingURL)
	}
	os.Exit(ecode)
}
示例#19
0
// If we're not running on GCE (e.g. dev mode on localhost) and have
// no other way to get the info, the error value is is errNoRefresh.
func (h *DeployHandler) authenticatedClient() (project string, hc *http.Client, err error) {
	project = os.Getenv("CAMLI_GCE_PROJECT")
	accountFile := os.Getenv("CAMLI_GCE_SERVICE_ACCOUNT")
	if project != "" && accountFile != "" {
		data, errr := ioutil.ReadFile(accountFile)
		err = errr
		if err != nil {
			return
		}
		jwtConf, errr := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/compute.readonly")
		err = errr
		if err != nil {
			return
		}
		hc = jwtConf.Client(context.Background())
		return
	}
	if !metadata.OnGCE() {
		err = errNoRefresh
		return
	}
	project, _ = metadata.ProjectID()
	hc, err = google.DefaultClient(oauth2.NoContext)
	return project, hc, err
}
示例#20
0
文件: gcs.go 项目: ably-forks/flynn
func NewGCS(name string, info map[string]string) (Backend, error) {
	b := &gcsBackend{
		name:       name,
		bucketName: info["bucket"],
	}
	keyJSON := []byte(info["key"])

	if b.bucketName == "" {
		return nil, fmt.Errorf("blobstore: missing Google Cloud Storage bucket param for %s", name)
	}
	if len(keyJSON) == 0 {
		return nil, fmt.Errorf("blobstore: missing Google Cloud Storage key JSON param for %s", name)
	}

	jwtToken, err := google.JWTConfigFromJSON(keyJSON, "https://www.googleapis.com/auth/devstorage.read_write")
	if err != nil {
		return nil, fmt.Errorf("blobstore: error loading Google Cloud Storage JSON key: %s", err)
	}
	tokenSource := jwtToken.TokenSource(context.Background())

	// Test getting an OAuth token so we can disambiguate an issue with the
	// token and an issue with the bucket permissions below.
	if _, err := tokenSource.Token(); err != nil {
		return nil, fmt.Errorf("blobstore: error getting Google Cloud Storage OAuth token: %s", err)
	}

	pemBlock, _ := pem.Decode(jwtToken.PrivateKey)
	privateKey, err := x509.ParsePKCS8PrivateKey(pemBlock.Bytes)
	if err != nil {
		return nil, fmt.Errorf("blobstore: error decoding Google Cloud Storage private key: %s", err)
	}
	rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey)
	if !ok {
		return nil, fmt.Errorf("blobstore: unexpected Google Cloud Storage key type: %T", privateKey)
	}
	b.signOpts = func() *storage.SignedURLOptions {
		return &storage.SignedURLOptions{
			GoogleAccessID: jwtToken.Email,
			SignBytes: func(b []byte) ([]byte, error) {
				digest := sha256.Sum256(b)
				return rsa.SignPKCS1v15(rand.Reader, rsaPrivateKey, crypto.SHA256, digest[:])
			},
			Method:  "GET",
			Expires: time.Now().Add(10 * time.Minute),
		}
	}

	client, err := storage.NewClient(context.Background(), option.WithTokenSource(tokenSource))
	if err != nil {
		return nil, fmt.Errorf("blobstore: error creating Google Cloud Storage client: %s", err)
	}
	b.bucket = client.Bucket(b.bucketName)

	_, err = b.bucket.Attrs(context.Background())
	if err != nil {
		return nil, fmt.Errorf("blobstore: error checking Google Cloud Storage bucket %q existence, ensure that it exists and Owner access for %s is included the bucket ACL: %q", b.bucketName, jwtToken.Email, err)
	}
	return b, nil
}
示例#21
0
文件: google.go 项目: koding/koding
func (c *Cred) ComputeService() (*compute.Service, error) {
	cfg, err := google.JWTConfigFromJSON([]byte(c.Credentials), compute.ComputeScope)
	if err != nil {
		return nil, err
	}

	return compute.New(cfg.Client(context.Background()))
}
示例#22
0
文件: gce.go 项目: hanscj1/images
// New returns a new instance of GceImages
func New(conf *GCEConfig) (*GceImages, error) {
	var err error
	if conf.ProjectID == "" {
		return nil, errors.New("ProjectID is not set. Please check your configuration.")
	}

	// increase the timeout. Also we need to pass the client with the context itself
	timeout := time.Second * 30
	ctx := context.WithValue(oauth2.NoContext, oauth2.HTTPClient, &http.Client{
		Transport: &http.Transport{TLSHandshakeTimeout: timeout},
		Timeout:   timeout,
	})

	var client *http.Client

	// allowed scopes
	scopes := []string{compute.ComputeScope}

	// Recommended way is explicit passing of credentials json which can be
	// downloaded from console.developers.google under APIs & Auth/Credentials
	// section
	if conf.AccountFile != "" {
		// expand shell meta character
		path, err := homedir.Expand(conf.AccountFile)
		if err != nil {
			return nil, err
		}

		jsonContent, err := ioutil.ReadFile(path)
		if err != nil {
			return nil, err
		}

		jtwConfig, err := google.JWTConfigFromJSON(jsonContent, scopes...)
		if err != nil {
			return nil, err
		}

		client = jtwConfig.Client(ctx)
	} else {
		// Look for application default credentials, for more details, see:
		// https://developers.google.com/accounts/docs/application-default-credentials
		client, err = google.DefaultClient(ctx, scopes...)
		if err != nil {
			return nil, err
		}
	}

	svc, err := compute.New(client)
	if err != nil {
		return nil, err
	}

	return &GceImages{
		svc:    compute.NewImagesService(svc),
		config: conf,
	}, nil
}
示例#23
0
// New returns http client which includes the credentials to access androidpublisher API.
// You should create a service account for your project at
// https://console.developers.google.com and download a JSON key file to set this argument.
func New(jsonKey []byte) (Client, error) {
	ctx := context.WithValue(oauth2.NoContext, oauth2.HTTPClient, &http.Client{
		Timeout: timeout,
	})

	conf, err := google.JWTConfigFromJSON(jsonKey, androidpublisher.AndroidpublisherScope)

	return Client{conf.Client(ctx)}, err
}
示例#24
0
func getConfig(scope ...string) (config *jwt.Config, err error) {
	secret := os.Getenv(serviceSecretEnv)
	if secret == "" {
		err = fmt.Errorf("%q environment variable not set", serviceSecretEnv)
		return
	}

	config, err = google.JWTConfigFromJSON([]byte(secret), scope...)
	return
}
示例#25
0
func (h *DeployHandler) refreshZones() error {
	h.zonesMu.Lock()
	defer h.zonesMu.Unlock()
	defer func() {
		h.regions = make([]string, 0, len(h.zones))
		for r, _ := range h.zones {
			h.regions = append(h.regions, r)
		}
	}()
	// TODO(mpl): get projectID and access tokens from metadata once camweb is on GCE.
	accountFile := os.Getenv("CAMLI_GCE_SERVICE_ACCOUNT")
	if accountFile == "" {
		h.Printf("No service account to query for the zones, using hard-coded ones instead.")
		h.zones = backupZones
		return nil
	}
	project := os.Getenv("CAMLI_GCE_PROJECT")
	if project == "" {
		h.Printf("No project we can query on to get the zones, using hard-coded ones instead.")
		h.zones = backupZones
		return nil
	}
	data, err := ioutil.ReadFile(accountFile)
	if err != nil {
		return err
	}
	conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/compute.readonly")
	if err != nil {
		return err
	}
	s, err := compute.New(conf.Client(oauth2.NoContext))
	if err != nil {
		return err
	}
	rl, err := compute.NewRegionsService(s).List(project).Do()
	if err != nil {
		return fmt.Errorf("could not get a list of regions: %v", err)
	}
	h.zones = make(map[string][]string)
	for _, r := range rl.Items {
		zones := make([]string, 0, len(r.Zones))
		for _, z := range r.Zones {
			zone := path.Base(z)
			if zone == "europe-west1-a" {
				// Because even though the docs mark it as deprecated, it still shows up here, go figure.
				continue
			}
			zone = strings.Replace(zone, r.Name, "", 1)
			zones = append(zones, zone)
		}
		h.zones[r.Name] = zones
	}
	return nil
}
示例#26
0
文件: dial.go 项目: naunga/vault
func serviceAcctTokenSource(ctx context.Context, filename string, scope ...string) (oauth2.TokenSource, error) {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, fmt.Errorf("cannot read service account file: %v", err)
	}
	cfg, err := google.JWTConfigFromJSON(data, scope...)
	if err != nil {
		return nil, fmt.Errorf("google.JWTConfigFromJSON: %v", err)
	}
	return cfg.TokenSource(ctx), nil
}
示例#27
0
文件: gcp.go 项目: ycaihua/gizmo
func (g Config) contextFromToken(scopes ...string) (context.Context, error) {
	conf, err := google.JWTConfigFromJSON(
		[]byte(g.Token),
		scopes...,
	)
	if err != nil {
		log.Print("probs with token:", g.Token)
		return nil, err
	}

	return cloud.NewContext(g.ProjectID, conf.Client(oauth2.NoContext)), nil
}
示例#28
0
func getServiceAccountClient(keyJsonfilePath string) (*http.Client, error) {
	data, err := ioutil.ReadFile(os.ExpandEnv(keyJsonfilePath))
	if err != nil {
		return nil, errors.Wrap(err, "error opening credentials file")
	}
	conf, err := google.JWTConfigFromJSON(data, storageConfig.Scopes...)
	if err != nil {
		return nil, errors.Wrap(err, "error processing credentials")
	}
	ctxWithSpecialClient := oauthutil.Context()
	return oauth2.NewClient(ctxWithSpecialClient, conf.TokenSource(ctxWithSpecialClient)), nil
}
示例#29
0
文件: client.go 项目: aaijazi/grpc-go
func getToken() *oauth2.Token {
	jsonKey := getServiceAccountJSONKey()
	config, err := google.JWTConfigFromJSON(jsonKey, *oauthScope)
	if err != nil {
		grpclog.Fatalf("Failed to get the config: %v", err)
	}
	token, err := config.TokenSource(context.Background()).Token()
	if err != nil {
		grpclog.Fatalf("Failed to get the token: %v", err)
	}
	return token
}
示例#30
0
func getContext(jsonPrivateKeyFilepath string, projectID string) (context.Context, error) {
	jsonKey, err := ioutil.ReadFile(jsonPrivateKeyFilepath)
	if err != nil {
		return nil, err
	}
	conf, err := google.JWTConfigFromJSON(jsonKey, storage.ScopeFullControl)
	if err != nil {
		return nil, err
	}
	ctx := cloud.NewContext(projectID, conf.Client(oauth2.NoContext))
	return ctx, nil
}