diff options
| author | Petter Rasmussen | 2013-01-01 20:48:15 +0100 |
|---|---|---|
| committer | Petter Rasmussen | 2013-01-01 20:48:15 +0100 |
| commit | 2f4fabf7bb74b42a7aa54c5b02538e4ca337361f (patch) | |
| tree | db087fb26d0e97ab494f8f8684dc0441630efb75 /auth | |
| download | gdrive-2f4fabf7bb74b42a7aa54c5b02538e4ca337361f.tar.bz2 | |
version 1
Diffstat (limited to 'auth')
| -rw-r--r-- | auth/auth.go | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/auth/auth.go b/auth/auth.go new file mode 100644 index 0000000..c4a67e3 --- /dev/null +++ b/auth/auth.go @@ -0,0 +1,68 @@ +package auth + +import ( + "net/http" + "fmt" + "code.google.com/p/goauth2/oauth" + "../util" +) + +// Get auth code from user +func promptUserForAuthCode(config *oauth.Config) string { + authUrl := config.AuthCodeURL("state") + fmt.Println("Go to the following link in your browser:") + fmt.Printf("%v\n\n", authUrl) + return util.Prompt("Enter verification code: ") +} + +// Returns true if we have a valid cached token +func hasValidToken(cacheFile oauth.CacheFile, transport *oauth.Transport) bool { + // Check if we have a cached token + token, err := cacheFile.Token() + if err != nil { + return false + } + + // Refresh token if its expired + if token.Expired() { + transport.Token = token + err = transport.Refresh() + if err != nil { + fmt.Println(err) + return false + } + } + return true +} + +func GetOauth2Client(clientId, clientSecret, cachePath string) (*http.Client, error) { + cacheFile := oauth.CacheFile(cachePath) + + config := &oauth.Config{ + ClientId: clientId, + ClientSecret: clientSecret, + Scope: "https://www.googleapis.com/auth/drive", + RedirectURL: "urn:ietf:wg:oauth:2.0:oob", + AuthURL: "https://accounts.google.com/o/oauth2/auth", + TokenURL: "https://accounts.google.com/o/oauth2/token", + TokenCache: cacheFile, + } + + transport := &oauth.Transport{ + Config: config, + Transport: http.DefaultTransport, + } + + // Return client if we have a valid token + if hasValidToken(cacheFile, transport) { + return transport.Client(), nil + } + + // Get auth code from user and request a new token + code := promptUserForAuthCode(config) + _, err := transport.Exchange(code) + if err != nil { + return nil, err + } + return transport.Client(), nil +} |
