Example #1
0
func tokenFromWeb(g_config *oauth.Config) *oauth.Token {
	ch := make(chan string)
	randState := fmt.Sprintf("st%d", time.Now())

	var listener *net.TCPListener

	go serveCallback(listener, randState, ch)
	defer listener.Close()

	g_config.RedirectURL = "http://localhost:8080/callback"
	authUrl := g_config.AuthCodeURL(randState)
	go openUrl(authUrl)
	log.Printf("Authorize this app at: %s", authUrl)
	code := <-ch
	log.Printf("Got code: %s", code)

	t := &oauth.Transport{
		Config:    g_config,
		Transport: condDebugTransport(http.DefaultTransport),
	}
	_, err := t.Exchange(code)
	if err != nil {
		log.Fatalf("Token exchange error: %v", err)
	}
	return t.Token
}
Example #2
0
// Handle register the passed http.HandleFunc to be executed when
// a request matches path. The HandleFunc will receive the oauth2
// code corresponding to the passed oauth.Config as form values.
func HandleFunc(path string, h http.HandlerFunc, cfg *oauth.Config) error {
	mutex.Lock()
	defer mutex.Unlock()

	u, err := url.Parse(cfg.RedirectURL)
	if err != nil {
		return fmt.Errorf("bad redirect URL: %v", err)
	}
	if u.Path != CallbackPath {
		return fmt.Errorf("RedirectURL has to point to %q, it points to %q", CallbackPath, u.Path)
	}

	handlers[path] = h
	rh := http.RedirectHandler(cfg.AuthCodeURL(path), http.StatusFound)
	http.Handle(path, rh)
	return nil
}
Example #3
0
func authRefreshToken(c *oauth.Config) (*oauth.Token, error) {
	l, err := net.Listen("tcp", "localhost:8016")
	defer l.Close()
	if err != nil {
		return nil, err
	}
	open.Run(c.AuthCodeURL(""))
	var token *oauth.Token
	done := make(chan struct{})
	f := func(w http.ResponseWriter, r *http.Request) {
		code := r.FormValue("code")
		transport := &oauth.Transport{Config: c}
		token, err = transport.Exchange(code)
		done <- struct{}{}
	}
	go http.Serve(l, http.HandlerFunc(f))
	<-done
	return token, err
}
Example #4
0
func tokenFromWeb(g_config *oauth.Config) *oauth.Token {
	ch := make(chan string)
	randState := fmt.Sprintf("st%d", time.Now())
	ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		if req.URL.Path == "/favicon.ico" {
			http.Error(rw, "", 404)
			return
		}
		if req.FormValue("state") != randState {
			log.Printf("State doesn't match: req = %#v", req)
			http.Error(rw, "", 500)
			return
		}
		if code := req.FormValue("code"); code != "" {
			fmt.Fprintf(rw, "<h1>Success</h1>Authorized.")
			rw.(http.Flusher).Flush()
			ch <- code
			return
		}
		log.Printf("no code")
		http.Error(rw, "", 500)
	}))
	defer ts.Close()

	g_config.RedirectURL = ts.URL
	fmt.Println(ts.URL)
	authUrl := g_config.AuthCodeURL(randState)
	go openUrl(authUrl)
	log.Printf("Authorize this app at: %s", authUrl)
	code := <-ch
	log.Printf("Got code: %s", code)

	t := &oauth.Transport{
		Config:    g_config,
		Transport: condDebugTransport(http.DefaultTransport),
	}
	_, err := t.Exchange(code)
	if err != nil {
		log.Fatalf("Token exchange error: %v", err)
	}
	return t.Token
}
// buildOAuthHTTPClient takes the user through the three-legged OAuth flow. Opens a browser in the native OS or
// outputs a URL, blocking until the redirect completes to the /oauth2callback URI.
// Returns an instance of an HTTP client that can be passed to the constructor of the YouTube client.
func buildOAuthHTTPClient(config *oauth.Config) (*http.Client, error) {
	transport := &oauth.Transport{Config: config}

	// Try to read the token from the cache file.
	// If there's an error, the token is invalid or doesn't exist, do the 3-legged OAuth flow.
	token, err := config.TokenCache.Token()
	if err != nil {

		// Make a channel for the web server to communicate with us on to tell us we have a code
		codeChannel := make(chan string)

		// Start web server. This is how this program receives the authorization code when the browser redirects.
		err := startWebServer(codeChannel)
		if err != nil {
			return nil, err
		}

		// Open url in browser
		url := config.AuthCodeURL("")
		err = openUrl(url)
		if err != nil {
			fmt.Println("Visit the URL below to get a code. This program will pause until the site is visted.")
		} else {
			fmt.Println("Your browser has been opened to an authorization URL. This program will resume once authorization has been provided.\n")
		}
		fmt.Println(url)

		// Block, wait for the web server to get the code back
		code := <-codeChannel

		// This will take care of caching the code on the local filesystem, if necessary, as long as the TokenCache
		// attribute in the config is set
		token, err = transport.Exchange(code)
		if err != nil {
			return nil, err
		}
	}

	transport.Token = token
	return transport.Client(), nil
}
Example #6
0
// RunFlowWithTransport runs through a 3LO OAuth 2.0 flow to get credentials for
// Google Storage using the specified HTTP transport.
func RunFlowWithTransport(config *oauth.Config, transport http.RoundTripper) (*http.Client, error) {
	if config == nil {
		config = DefaultOAuthConfig("")
	}
	oauthTransport := &oauth.Transport{
		Config:    config,
		Transport: transport,
	}
	if _, err := config.TokenCache.Token(); err != nil {
		url := config.AuthCodeURL("")
		fmt.Printf(`Your browser has been opened to visit:

  %s

Enter the verification code:`, url)
		var code string
		fmt.Scan(&code)
		if _, err := oauthTransport.Exchange(code); err != nil {
			return nil, fmt.Errorf("Failed exchange: %s", err)
		}
	}

	return oauthTransport.Client(), nil
}
Example #7
0
func tokenFromWeb(config *oauth.Config) *oauth.Token {
	randState := fmt.Sprintf("st%d", time.Now().UnixNano())

	config.RedirectURL = RedirectURI
	authURL := config.AuthCodeURL(randState)

	log.Info("Opening auth URL in browser.")
	log.Info(authURL)
	log.Info("If the URL doesn't open please open it manually and copy the code here.")
	openURL(authURL)
	code := getCodeFromStdin()

	log.Infof("Got code: %s", code)

	t := &oauth.Transport{
		Config:    config,
		Transport: http.DefaultTransport,
	}
	_, err := t.Exchange(code)
	if err != nil {
		log.Fatalf("Token exchange error: %v", err)
	}
	return t.Token
}
Example #8
0
func tokenFromWeb(config *oauth.Config) *oauth.Token {
	ch := make(chan string)
	randState := fmt.Sprintf("st%d", time.Now().UnixNano())
	http.HandleFunc("/auth", func(rw http.ResponseWriter, req *http.Request) {
		if req.FormValue("state") != randState {
			log.Printf("State doesn't match: req = %#v", req)
			http.Error(rw, "", 500)
			return
		}
		if code := req.FormValue("code"); code != "" {
			fmt.Fprintf(rw, "<h1>Success</h1>Authorized.")
			rw.(http.Flusher).Flush()
			ch <- code
			return
		}
		log.Printf("no code")
		http.Error(rw, "", 500)
	})

	config.RedirectURL = fmt.Sprintf("http://localhost:%s/auth", *port)
	authUrl := config.AuthCodeURL(randState)
	go openUrl(authUrl)
	log.Printf("Authorize this app at: %s", authUrl)
	code := <-ch
	log.Printf("Got code: %s", code)

	t := &oauth.Transport{
		Config:    config,
		Transport: http.DefaultTransport,
	}
	_, err := t.Exchange(code)
	if err != nil {
		log.Fatalf("Token exchange error: %v", err)
	}
	return t.Token
}
Example #9
0
// 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: ")
}
Example #10
0
File: oauth.go Project: 0x7cc/rsc
// Token obtains an OAuth token, keeping a cached copy in file.
// If the file name is not an absolute path, it is interpreted relative to the
// user's home directory.
func Token(file string, cfg *oauth.Config) (*oauth.Transport, error) {
	if !filepath.IsAbs(file) {
		file = filepath.Join(os.Getenv("HOME"), file)
	}
	cfg1 := *cfg
	cfg = &cfg1
	cfg.TokenCache = oauth.CacheFile(file)
	tok, err := cfg.TokenCache.Token()
	if err == nil {
		return &oauth.Transport{Config: cfg, Token: tok}, nil
	}

	// Start HTTP server on localhost.
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		var err1 error
		if l, err1 = net.Listen("tcp6", "[::1]:0"); err1 != nil {
			return nil, fmt.Errorf("oauthprompt.Token: starting HTTP server: %v", err)
		}
	}

	type done struct {
		err  error
		code string
	}
	ch := make(chan done, 100)

	randState, err := randomID()
	if err != nil {
		return nil, err
	}

	cfg.RedirectURL = "http://" + l.Addr().String() + "/done"
	authURL := cfg1.AuthCodeURL(randState)

	handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path == "/auth" {
			http.Redirect(w, req, authURL, 301)
			return
		}
		if req.URL.Path != "/done" {
			http.Error(w, "", 404)
			return
		}
		if req.FormValue("state") != randState {
			ch <- done{err: fmt.Errorf("oauthprompt.Token: incorrect response")}
			http.Error(w, "", 500)
			return
		}
		if code := req.FormValue("code"); code != "" {
			ch <- done{code: code}
			w.Write([]byte(success))
			return
		}
		http.Error(w, "", 500)
	})

	srv := &http.Server{Handler: handler}
	go srv.Serve(l)
	if err := openURL("http://" + l.Addr().String() + "/auth"); err != nil {
		l.Close()
		return nil, err
	}
	d := <-ch
	l.Close()

	if d.err != nil {
		return nil, err
	}

	tr := &oauth.Transport{Config: &cfg1}
	_, err = tr.Exchange(d.code)
	if err != nil {
		return nil, err
	}
	return tr, nil
}