From bb8fe1aa33161f7dade7afcd842d32df4c73354e Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Fri, 15 Aug 2014 12:47:05 -0700 Subject: [PATCH] GCE setup tool: more graceful OAuth setup Change-Id: I28893735c49da18d3890a0df07b071048c29ba68 --- misc/gce/.gitignore | 2 +- misc/gce/create.go | 28 +++++++++++++++++++--------- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/misc/gce/.gitignore b/misc/gce/.gitignore index 30ce415ab..3433d1356 100644 --- a/misc/gce/.gitignore +++ b/misc/gce/.gitignore @@ -1,3 +1,3 @@ client-id.dat client-secret.dat -auth-code.dat +token.dat diff --git a/misc/gce/create.go b/misc/gce/create.go index 2db1dd25c..042ce294b 100644 --- a/misc/gce/create.go +++ b/misc/gce/create.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "flag" "io/ioutil" "log" @@ -26,6 +27,8 @@ func readFile(v string) string { } var config = &oauth.Config{ + // The client-id and secret should be for an "Installed Application" when using + // the CLI. Later we'll use a web application with a callback. ClientId: readFile("client-id.dat"), ClientSecret: readFile("client-secret.dat"), Scope: strings.Join([]string{ @@ -49,19 +52,26 @@ func main() { imageURL := "https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images/coreos-alpha-402-2-0-v20140807" machType := prefix + "/zones/" + *zoneFlag + "/machineTypes/" + *machFlag - if _, err := os.Stat("auth-code.dat"); err != nil { - log.Printf("No auth code in file auth-code.dat. Get auth code from %v", config.AuthCodeURL("my-state")) - return - } - authCode := readFile("auth-code.dat") - tr := &oauth.Transport{ Config: config, } - t, err := tr.Exchange(authCode) + + tokenCache := oauth.CacheFile("token.dat") + token, err := tokenCache.Token() if err != nil { - log.Fatal(err) + log.Printf("Error getting token from %s: %v", string(tokenCache), err) + log.Printf("Get auth code from %v", config.AuthCodeURL("my-state")) + os.Stdout.Write([]byte("\nEnter auth code: ")) + sc := bufio.NewScanner(os.Stdin) + sc.Scan() + authCode := strings.TrimSpace(sc.Text()) + token, err = tr.Exchange(authCode) + if err != nil { + log.Fatalf("Error exchanging auth code for a token: %v", err) + } + tokenCache.PutToken(token) } - log.Printf("Got token: %#v", t) + + log.Printf("Got token: %#v", token) _, _ = machType, imageURL }