Пример #1
0
// parseJSONAuthFile parses a file, and extracts the OAuth2 credentials within.
func parseJSONAuthFile(r io.Reader) (cloud.Credential, error) {
	creds, err := google.ParseJSONKey(r)
	if err != nil {
		return cloud.Credential{}, errors.Trace(err)
	}
	return cloud.NewCredential(cloud.OAuth2AuthType, map[string]string{
		credAttrProjectID:   creds.ProjectID,
		credAttrClientID:    creds.ClientID,
		credAttrClientEmail: creds.ClientEmail,
		credAttrPrivateKey:  string(creds.PrivateKey),
	}), nil
}
Пример #2
0
// parseJSONAuthFile parses the file with the given path, and extracts
// the OAuth2 credentials within.
func parseJSONAuthFile(filename string) (cloud.Credential, error) {
	authFile, err := os.Open(filename)
	if err != nil {
		return cloud.Credential{}, errors.Trace(err)
	}
	defer authFile.Close()
	creds, err := google.ParseJSONKey(authFile)
	if err != nil {
		return cloud.Credential{}, errors.Trace(err)
	}
	return cloud.NewCredential(cloud.OAuth2AuthType, map[string]string{
		"project-id":   creds.ProjectID,
		"client-id":    creds.ClientID,
		"client-email": creds.ClientEmail,
		"private-key":  string(creds.PrivateKey),
	}), nil
}
Пример #3
0
func (s *credentialsSuite) TestParseJSONKey(c *gc.C) {
	original := `
{
    "private_key_id": "mnopq",
    "private_key": "<some-key>",
    "client_email": "*****@*****.**",
    "client_id": "abc",
    "type": "service_account"
}`[1:]
	creds, err := google.ParseJSONKey(bytes.NewBufferString(original))
	c.Assert(err, jc.ErrorIsNil)

	jsonKey := creds.JSONKey
	creds.JSONKey = nil
	c.Check(creds, jc.DeepEquals, &google.Credentials{
		ClientID:    "abc",
		ClientEmail: "*****@*****.**",
		PrivateKey:  []byte("<some-key>"),
	})
	c.Check(string(jsonKey), gc.Equals, original)
}
Пример #4
0
// parseCredentials extracts the OAuth2 info from the config from the
// individual fields (falling back on the JSON file).
func parseCredentials(cfg *config.Config) (*google.Credentials, error) {
	attrs := cfg.UnknownAttrs()

	// Try the auth fields first.
	values := make(map[string]string)
	for _, field := range configAuthFields {
		if existing, ok := attrs[field].(string); ok && existing != "" {
			for key, candidate := range osEnvFields {
				if field == candidate {
					values[key] = existing
					break
				}
			}
		}
	}
	if len(values) > 0 {
		creds, err := google.NewCredentials(values)
		if err != nil {
			return nil, errors.Trace(err)
		}
		return creds, nil
	}

	// Fall back to the auth file.
	filename, ok := attrs[cfgAuthFile].(string)
	if !ok || filename == "" {
		// The missing credentials will be caught later.
		return nil, nil
	}
	authFile, err := os.Open(filename)
	if err != nil {
		return nil, errors.Trace(err)
	}
	defer authFile.Close()
	creds, err := google.ParseJSONKey(authFile)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return creds, nil
}