// Function that handles the callback from the Google server func handleOAuth2Callback(w http.ResponseWriter, r *http.Request) { //Get the code from the response code := r.FormValue("code") t := &oauth.Transport{oauth.Config: oauthCfg} // Exchange the received code for a token tok, _ := t.Exchange(code) { tokenCache := oauth.CacheFile("./request.token") err := tokenCache.PutToken(tok) if err != nil { log.Fatal("Cache write:", err) } log.Printf("Token is cached in %v\n", tokenCache) token = tok.AccessToken } /* // Skip TLS Verify t.Transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } */ userInfoTemplate.Execute(w, nil) }
func main() { flag.Parse() // Set up a configuration. config := &oauth.Config{ ClientId: *clientId, ClientSecret: *clientSecret, RedirectURL: *redirectURL, Scope: *scope, AuthURL: *authURL, TokenURL: *tokenURL, TokenCache: oauth.CacheFile(*cachefile), } // Set up a Transport using the config. transport := &oauth.Transport{Config: config} // Try to pull the token from the cache; if this fails, we need to get one. token, err := config.TokenCache.Token() if err != nil { if *clientId == "" || *clientSecret == "" { flag.Usage() fmt.Fprint(os.Stderr, usageMsg) os.Exit(2) } if *code == "" { // Get an authorization code from the data provider. // ("Please ask the user if I can access this resource.") url := config.AuthCodeURL("") fmt.Print("Visit this URL to get a code, then run again with -code=YOUR_CODE\n\n") fmt.Println(url) return } // Exchange the authorization code for an access token. // ("Here's the code you gave the user, now give me a token!") token, err = transport.Exchange(*code) if err != nil { log.Fatal("Exchange:", err) } // (The Exchange method will automatically cache the token.) fmt.Printf("Token is cached in %v\n", config.TokenCache) } // Make the actual request using the cached token to authenticate. // ("Here's the token, let me in!") transport.Token = token // Make the request. r, err := transport.Client().Get(*requestURL) if err != nil { log.Fatal("Get:", err) } defer r.Body.Close() // Write the response to standard output. io.Copy(os.Stdout, r.Body) // Send final carriage return, just to be neat. fmt.Println() }
func setupOAuthClient() error { config := &oauth.Config{ ClientId: "999119582588-h7kpj5pcm6d9solh5lgrbusmvvk4m9dn.apps.googleusercontent.com", ClientSecret: "8YLFgOhXIELWbO-NtF3iqIQz", Scope: storage.DevstorageRead_writeScope, AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", TokenCache: oauth.CacheFile(*tokenCache), RedirectURL: "oob", } transport := &oauth.Transport{Config: config} if token, err := config.TokenCache.Token(); err != nil { url := transport.Config.AuthCodeURL("") fmt.Println("Visit the following URL, obtain an authentication" + "code, and enter it below.") fmt.Println(url) fmt.Print("Enter authentication code: ") code := "" if _, err := fmt.Scan(&code); err != nil { return err } if _, err := transport.Exchange(code); err != nil { return err } } else { transport.Token = token } oauthClient = transport.Client() return nil }
// Create a new instance of Client func NewClient(cid string, csec string, redurl string) *Client { config := &oauth.Config{ ClientId: cid, ClientSecret: csec, Scope: "non-expiring", AuthURL: AuthUrl, TokenURL: TokenUrl, RedirectURL: redurl, TokenCache: oauth.CacheFile(CacheFile), } //fmt.Printf("%+v\n", config) transport := &oauth.Transport{Config: config} token, err := config.TokenCache.Token() if err != nil { if code == "" { url := config.AuthCodeURL("") fmt.Println(url) return nil } token, err = transport.Exchange(code) } transport.Token = token return &Client{ HttpClient: transport.Client(), Token: token, } }
// readConfig reads the configuration from clientSecretsFile. Returns an oauth configuration // object to be used with the Google API client func readConfig() (*oauth.Config, error) { // Let's read the configuration configFile := new(Config) data, err := ioutil.ReadFile(*clientSecretsFile) if err != nil { pwd, _ := os.Getwd() clientSecretsFileFullPath := path.Join(pwd, *clientSecretsFile) return nil, fmt.Errorf(missingClientSecretsMessage, clientSecretsFileFullPath) } err = json.Unmarshal(data, &configFile) if err != nil { return nil, err } if len(configFile.Installed.RedirectURIs) < 1 { return nil, errors.New("Configuration file must contain at least one redirect URI") } return &oauth.Config{ ClientId: configFile.Installed.ClientId, ClientSecret: configFile.Installed.ClientSecret, Scope: youtube.YoutubeReadonlyScope, AuthURL: configFile.Installed.AuthURI, TokenURL: configFile.Installed.TokenURI, RedirectURL: configFile.Installed.RedirectURIs[0], TokenCache: oauth.CacheFile(*cachefile), // This gives us a refresh token so we can use this access token indefinitely AccessType: "offline", // If we want a refresh token, we must set this to force an approval prompt or this // won't work ApprovalPrompt: "force", }, nil }
// Internal function to get a token, using vars defined in get_oauth_token. // I need better terminology. func get_token(client *client_info, cachefile_name string) (*oauth.Transport, *oauth.Token, *oauth.Config, error) { var ( scope = "https://www.google.com/m8/feeds" authURL = "https://accounts.google.com/o/oauth2/auth" redirectURL = "urn:ietf:wg:oauth:2.0:oob" tokenURL = "https://accounts.google.com/o/oauth2/token" cachefile = cachefile_name ) config := &oauth.Config{ ClientId: client.Id, ClientSecret: client.Secret, RedirectURL: redirectURL, Scope: scope, AuthURL: authURL, TokenURL: tokenURL, TokenCache: oauth.CacheFile(cachefile), } // Set up a Transport using the config. transport := &oauth.Transport{Config: config} // Try to pull the token from the cache; if this fails, we need to get one. token, err := config.TokenCache.Token() if err != nil { if client.Id == "" || client.Secret == "" { log.Printf("Error in obtaining a token: %s\n", err) log.Fatalf("cachefile is: %s\n", cachefile) } log.Println("Err is not nil") log.Println("token is ", token) log.Println("transport is ", transport) log.Println("config is ", config) } return transport, token, config, err }
// Create a new instance of Client func NewClient(cid string, csec string, redurl string) *Client { config := &oauth.Config{ ClientId: cid, ClientSecret: csec, Scope: "public", AuthURL: AuthUrl, TokenURL: TokenUrl, RedirectURL: redurl, TokenCache: oauth.CacheFile(CacheFile), } // fmt.Printf("%+v\n", config) transport := &oauth.Transport{Config: config} token, err := config.TokenCache.Token() if err != nil { return &Client{ Transport: transport, AuthCodeUrl: config.AuthCodeURL(""), } } else { c := Client{Transport: transport} c.setToken(token) return &c } }
// readConfig reads the configuration from clientSecretsFile. // It returns an oauth configuration object for use with the Google API client. func readConfig(scope string, cfg *Config) (*oauth.Config, error) { var redirectUri string if len(cfg.Web.RedirectURIs) > 0 { redirectUri = cfg.Web.RedirectURIs[0] } else if len(cfg.Installed.RedirectURIs) > 0 { redirectUri = cfg.Installed.RedirectURIs[0] } else { return nil, errors.New("Must specify a redirect URI in config file or when creating OAuth client") } return &oauth.Config{ ClientId: cfg.Installed.ClientID, ClientSecret: cfg.Installed.ClientSecret, Scope: scope, AuthURL: cfg.Installed.AuthURI, TokenURL: cfg.Installed.TokenURI, RedirectURL: redirectUri, TokenCache: oauth.CacheFile(*cacheFile), // Get a refresh token so we can use the access token indefinitely AccessType: "offline", // If we want a refresh token, we must set this attribute // to force an approval prompt or the code won't work. ApprovalPrompt: "force", }, nil }
func NewGDriveFileSystem(clientId string, clientSecret string) *GDriveFileSystem { u, err := user.Current() tokenFile := u.HomeDir + "/.gdrive_token" if *tokenFileFlag != "" { tokenFile = *tokenFileFlag } config.TokenCache = oauth.CacheFile(tokenFile) config.ClientId = clientId config.ClientSecret = clientSecret transport := &oauth.Transport{ Config: config, Transport: &loggingTransport{http.DefaultTransport}, } obtainToken(transport) client, err := drive.New(transport.Client()) if err != nil { log.Errorf("An error occurred creating Drive client: %v\n", err) panic(-3) } fs := &GDriveFileSystem{ client: client, transport: transport, cache: gocache.New(5*time.Minute, 30*time.Second), } return fs }
func prepareNativeClient(data *oauthConfig) (*http.Client, error) { config := &oauth.Config{ ClientId: data.Installed.Client_Id, ClientSecret: data.Installed.Client_Secret, RedirectURL: data.Installed.Redirect_Uris[0], Scope: oauthScope, AuthURL: data.Installed.Auth_Uri, TokenURL: data.Installed.Token_Uri, TokenCache: oauth.CacheFile(".oauth2_cache.json"), } transport := &oauth.Transport{Config: config} token, err := config.TokenCache.Token() if err != nil { url := config.AuthCodeURL("") code := obtainOauthCode(url) token, err = transport.Exchange(code) if err != nil { return nil, err } } transport.Token = token client := transport.Client() return client, nil }
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 }
func main() { flag.Parse() config := &oauth.Config{ ClientId: "120233572441-d8vmojicfgje467joivr5a7j52dg2gnc.apps.googleusercontent.com", ClientSecret: "vfZkluBV6PTfGBWxfIIyXbMS", Scope: "https://www.googleapis.com/auth/calendar", AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", TokenCache: oauth.CacheFile(*cachefile), } transport := &oauth.Transport{Config: config} if token, err := config.TokenCache.Token(); err != nil { err = authenticate(transport) if err != nil { log.Fatalln("authenticate:", err) } } else { transport.Token = token } service, err := calendar.New(transport.Client()) if err != nil { log.Fatal(err) } calId, err := streakCalendarId(service) if err != nil { log.Fatal(err) } cal := &Calendar{ Id: calId, Service: service, } today := time.Now().Add(time.Duration(*offset) * day) today = parseDate(today.Format(dateFormat)) // normalize if *remove { err = cal.removeFromStreak(today) } else { err = cal.addToStreak(today) } if err != nil { log.Fatal(err) } var longest time.Duration cal.iterateEvents(func(e *calendar.Event, start, end time.Time) error { if d := end.Sub(start); d > longest { longest = d } return Continue }) fmt.Println("Longest streak:", int(longest/day), "days") }
func newConfig(cachePath string) *oauth.Config { return &oauth.Config{ ClientId: clientId, ClientSecret: clientSecret, RedirectURL: "urn:ietf:wg:oauth:2.0:oob", AuthURL: "https://auth.g5search.com/oauth/authorize", TokenURL: "https://auth.g5search.com/oauth/token", TokenCache: oauth.CacheFile(cachePath + "/g5_auth_token.json"), } }
func main() { httpClient := auth.AuthenticationRequest() token, _ := oauth.CacheFile("cache.json").Token() client := flowdock.NewClient(httpClient) messageList(client) messageStream(client, token.AccessToken) fmt.Println("Waiting for event") }
func main() { flag.Parse() config := &oauth.Config{ ClientId: os.Getenv("STREAK_CLIENT_ID"), ClientSecret: os.Getenv("STREAK_CLIENT_SECRET"), Scope: "https://www.googleapis.com/auth/calendar", AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", } transport := &oauth.Transport{Config: config} tokenCache := oauth.CacheFile(*cachefile) token, err := tokenCache.Token() if err != nil { log.Println("Cache read:", err) if *code == "" { url := config.AuthCodeURL("") fmt.Println("Visit this URL to get a code, then run again with -code=YOUR_CODE\n") fmt.Println(url) return } token, err = transport.Exchange(*code) if err != nil { log.Fatal("Exchange:", err) } err = tokenCache.PutToken(token) if err != nil { log.Println("Cache write:", err) } } transport.Token = token service, err = calendar.New(transport.Client()) if err != nil { log.Fatal(err) } calId, err := streakCalendarId() if err != nil { log.Fatal(err) } today := parseDate(time.Now().Add(time.Duration(*offset) * day).Format(dateFormat)) if *remove { _, err = removeFromStreak(calId, today) } else { _, err = addToStreak(calId, today) } if err != nil { log.Fatal(err) } }
func CreateGoogleOAuthConfig(client_id string, client_secret string, redirect_URL string, cache_file_path string) *oauth.Config { return &oauth.Config{ ClientId: client_id, ClientSecret: client_secret, AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", RedirectURL: redirect_URL, Scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me", TokenCache: oauth.CacheFile(cache_file_path), } }
func prepareClient() (*http.Client, error) { if oauthJsonFile == "" { return &http.Client{}, nil } jsonData, err := ioutil.ReadFile(oauthJsonFile) if err != nil { return nil, err } var data struct { Installed struct { Client_Id string Client_Secret string Redirect_Uris []string Auth_Uri string Token_Uri string } } err = json.Unmarshal(jsonData, &data) if err != nil { return nil, err } config := &oauth.Config{ ClientId: data.Installed.Client_Id, ClientSecret: data.Installed.Client_Secret, RedirectURL: data.Installed.Redirect_Uris[0], Scope: strings.Join([]string{ genomics.GenomicsScope, genomics.DevstorageRead_writeScope, }, " "), AuthURL: data.Installed.Auth_Uri, TokenURL: data.Installed.Token_Uri, TokenCache: oauth.CacheFile(".oauth2_cache.json"), } transport := &oauth.Transport{Config: config} token, err := config.TokenCache.Token() if err != nil { url := config.AuthCodeURL("") code := obtainOauthCode(url) token, err = transport.Exchange(code) if err != nil { return nil, err } } transport.Token = token client := transport.Client() return client, nil }
func OAuthConfig() *oauth.Config { var cfg = settings.Config() config := &oauth.Config{ ClientId: cfg.Github.ClientId, ClientSecret: cfg.Github.ClientSecret, RedirectURL: cfg.Github.RedirectUrl, Scope: cfg.Github.Scope, AuthURL: cfg.Github.AuthUrl, TokenURL: cfg.Github.TokenUrl, TokenCache: oauth.CacheFile(cfg.Github.TokenCache), } return config }
func OpenDrive(googleClientId string, googleClientSecret string, googleDomain string, cacheFile string) { googleWriterDomain = googleDomain GcacheFile = cacheFile GgoogleClientId = googleClientId GgoogleClientSecret = googleClientSecret // Settings for Google authorization. oauthConfig := &oauth.Config{ ClientId: googleClientId, ClientSecret: googleClientSecret, 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: oauth.CacheFile(cacheFile), } // Set up a Transport using the oauthConfig. oauthTransport = &oauth.Transport{ Config: oauthConfig, Transport: http.DefaultTransport, } // Try to pull the token from the cache; if this fails, we need to get one. token, err := oauthConfig.TokenCache.Token() if err != nil { // Get an authorization code from the user authUrl := oauthConfig.AuthCodeURL("state") log.Logf(l4g.INFO, "Go to the following link in your browser: %v", authUrl) // Read the code, and exchange it for a token. log.Logf(l4g.INFO, "Enter verification code: ") var code string fmt.Scanln(&code) token, err = oauthTransport.Exchange(code) if err != nil { l4g.Crashf("An error occurred exchanging the code: %v", err) } log.Logf(l4g.INFO, "Token is cached in %v", oauthConfig.TokenCache) } oauthTransport.Token = token oauthClient = oauthTransport.Client() // Create a new authorized Drive client. driveSvc, err = drive.New(oauthClient) if err != nil { l4g.Crashf("An error occurred creating Drive client: %v", err) } }
func Authorize(tokenDir, tokenFile string) { err := os.MkdirAll(tokenDir, 0777) if err != nil { fmt.Printf("Failed to create directory for the token at %s\n", tokenDir) } cachefile := filepath.Join(tokenDir, tokenFile) if clientId == "" { clientId = productionClientId } if clientSecret == "" { clientSecret = productionClientSecret } config := &oauth.Config{ ClientId: clientId, ClientSecret: clientSecret, RedirectURL: redirectURL, Scope: scope, AuthURL: authURL, TokenURL: tokenURL, TokenCache: oauth.CacheFile(cachefile), } transport := &oauth.Transport{Config: config} _, err = config.TokenCache.Token() // do we already have access? if err != nil { url := config.AuthCodeURL("") e := open.Run(url) if e != nil { fmt.Printf("Counldn't open the browser because %s\n", e.Error()) fmt.Println("Please open the following URL in your browser and paste the access code here:") fmt.Println(url) } else { fmt.Println("Openning the browser so you can approve the client access") } var s string fmt.Println("Authorization Code:") fmt.Scan(&s) _, err := transport.Exchange(s) if err != nil { log.Fatal("Exchange:", err) } fmt.Printf("Token is cached in %v\n", config.TokenCache) os.Exit(1) } }
// OAuthConfig returns a configuration for oauth with the specified scope. // If the given path for the cachefile is empty a default value is used. func OAuthConfig(cacheFilePath, scope string) *oauth.Config { if cacheFilePath == "" { cacheFilePath = "google_storage_token.data" } return &oauth.Config{ ClientId: "470362608618-nlbqngfl87f4b3mhqqe9ojgaoe11vrld.apps.googleusercontent.com", ClientSecret: "J4YCkfMXFJISGyuBuVEiH60T", Scope: scope, AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", RedirectURL: "urn:ietf:wg:oauth:2.0:oob", TokenCache: oauth.CacheFile(cacheFilePath), } }
func AuthenticationRequest(c *cli.Context) *http.Client { // Set up a configuration. config := &oauth.Config{ ClientId: c.String("id"), ClientSecret: c.String("secret"), RedirectURL: "urn:ietf:wg:oauth:2.0:oob", Scope: "", AuthURL: c.String("auth_url"), TokenURL: c.String("token_url"), TokenCache: oauth.CacheFile(c.String("cache")), } // Set up a Transport using the config. transport := &oauth.Transport{Config: config} // Try to pull the token from the cache; if this fails, we need to get one. token, err := config.TokenCache.Token() if err != nil { if c.String("id") == "" || c.String("secret") == "" { cli.ShowAppHelp(c) fmt.Fprint(os.Stderr, usageMsg) os.Exit(2) } if c.String("code") == "" { // Get an authorization code from the data provider. // ("Please ask the user if I can access this resource.") url := config.AuthCodeURL("") fmt.Println("Visit this URL to get a code, then run again with -code=YOUR_CODE\n") fmt.Println(url) os.Exit(0) } // Exchange the authorization code for an access token. // ("Here's the code you gave the user, now give me a token!") token, err = transport.Exchange(c.String("code")) if err != nil { log.Fatal("Exchange:", err) } // (The Exchange method will automatically cache the token.) fmt.Printf("Token is cached in %v\n", config.TokenCache) } // Make the actual request using the cached token to authenticate. // ("Here's the token, let me in!") transport.Token = token client := transport.Client() return client }
func initBuffer() (buffer *bufferapi.Client) { authToken := env.String("BUFFER_AUTH_TOKEN") clientId := env.String("BUFFER_CLIENT_ID") clientSecret := env.String("BUFFER_CLIENT_SECRET") bufferConfig := &oauth.Config{ ClientId: clientId, ClientSecret: clientSecret, Scope: "", AuthURL: "", TokenURL: "", TokenCache: oauth.CacheFile(""), } transport := &oauth.Transport{Config: bufferConfig} buffer = bufferapi.ClientFactory(authToken, transport) return }
func (s *BufferSuite) SetUpSuite(c *C) { err := loadConfig(s) if err != nil { c.Fatalf("%v", err) } config := &oauth.Config{ ClientId: s.ClientId, ClientSecret: s.ClientSecret, Scope: "", AuthURL: "", TokenURL: "", TokenCache: oauth.CacheFile(""), } transport := &oauth.Transport{Config: config} s.Buffer = ClientFactory(s.AuthToken, transport) }
func main() { flag.Parse() // Set up a configuration. config = &oauth.Config{ ClientId: *clientId, ClientSecret: *clientSecret, Scope: *apiURL, AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", TokenCache: oauth.CacheFile(*cachefile), RedirectURL: "http://gontacts.herokuapp.com/oauth2callback", } http.HandleFunc("/", handleRoot) http.HandleFunc("/auth", handleAuth) http.HandleFunc("/oauth2callback", handleOAuth2Callback) http.ListenAndServe(":"+os.Getenv("PORT"), nil) }
func GetConfig(provider string) (*oauth.Config, error) { sttngs, ok := settings[provider] if !ok { return nil, errors.New("Settings for the given provider (" + provider + ") are not available.") } // Set up a configuration. config := &oauth.Config{ ClientId: sttngs.ClientID, ClientSecret: sttngs.ClientSecret, RedirectURL: sttngs.UrlRedirect, Scope: sttngs.Scope, AuthURL: sttngs.UrlAuth, TokenURL: sttngs.UrlToken, TokenCache: oauth.CacheFile(sttngs.CacheFile), } return config, nil }
func (gd *GoogleDrive) CheckSize() (error, bool) { var c oauth.CacheFile = oauth.CacheFile(gd.authString) tok, err := c.Token() fmt.Println(err) t := &oauth.Transport{ Config: config, Transport: http.DefaultTransport, Token: tok, } // Create a new authorized Drive client. d, err := drive.New(t.Client()) if err != nil { fmt.Printf("An error occurred creating Drive client: %v\n", err) } a, err := d.About.Get().Do() if err != nil { fmt.Printf("An error occurred: %v\n", err) } return err, a.QuotaBytesTotal-a.QuotaBytesUsed >= 1024*1024 }
func GetClient(tokenDir, tokenFile, version string) Client { cachefile := filepath.Join(tokenDir, tokenFile) defaultUserAgent = "cx/" + version + " (" + runtime.GOOS + "; " + runtime.GOARCH + ")" config := &oauth.Config{ ClientId: clientId, ClientSecret: clientSecret, RedirectURL: redirectURL, Scope: scope, AuthURL: authURL, TokenURL: tokenURL, TokenCache: oauth.CacheFile(cachefile), } transport := &oauth.Transport{Config: config} token, _ := config.TokenCache.Token() transport.Token = token return Client{HTTP: transport.Client()} }
// Uploads a file to Google Drive func (gd *GoogleDrive) Upload(file string) string { // Generate a URL to visit for authorization. var c oauth.CacheFile = oauth.CacheFile(gd.authString) tok, _ := c.Token() t := &oauth.Transport{ Config: config, Transport: http.DefaultTransport, Token: tok, } // Create a new authorized Drive client. svc, err := drive.New(t.Client()) if err != nil { fmt.Printf("An error occurred creating Drive client: %v\n", err) } // Define the metadata for the file we are going to create. f := &drive.File{ Title: name, Description: DESCRIPTION, } // Read the file data that we are going to upload. m, err := os.Open(file) if err != nil { fmt.Printf("An error occurred reading the document: %v\n", err) } tStart := time.Now().Second() // Make the API request to upload metadata and file data. r, err := svc.Files.Insert(f).Media(m).Do() if err != nil { fmt.Printf("An error occurred uploading the document: %v\n", err) } tEnd := time.Now().Second() gd.totalSize += 1024 * 1024 gd.totalSize += uint32(tEnd - tStart) fmt.Printf("Created: ID=%v, Title=%v\n", r.Id, r.Title) return r.Id }
// readConfig reads the configuration from clientSecretsFile. // It returns an oauth configuration object for use with the Google API client. func readConfig(scope string) (*oauth.Config, error) { // Read the secrets file data, err := ioutil.ReadFile(*clientSecretsFile) if err != nil { pwd, _ := os.Getwd() fullPath := filepath.Join(pwd, *clientSecretsFile) return nil, fmt.Errorf(missingClientSecretsMessage, fullPath) } cfg := new(Config) err = json.Unmarshal(data, &cfg) if err != nil { return nil, err } var redirectUri string if len(cfg.Web.RedirectURIs) > 0 { redirectUri = cfg.Web.RedirectURIs[0] } else if len(cfg.Installed.RedirectURIs) > 0 { redirectUri = cfg.Installed.RedirectURIs[0] } else { return nil, errors.New("Must specify a redirect URI in config file or when creating OAuth client") } return &oauth.Config{ ClientId: cfg.Installed.ClientID, ClientSecret: cfg.Installed.ClientSecret, Scope: scope, AuthURL: cfg.Installed.AuthURI, TokenURL: cfg.Installed.TokenURI, RedirectURL: redirectUri, TokenCache: oauth.CacheFile(*cacheFile), // Get a refresh token so we can use the access token indefinitely AccessType: "offline", // If we want a refresh token, we must set this attribute // to force an approval prompt or the code won't work. ApprovalPrompt: "force", }, nil }