From 216ffb89e2a94a0e5f3dd6c764eccae557a7f31d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Wed, 9 Oct 2019 16:00:34 +0200 Subject: [PATCH] Use random available port number --- auth/oauth.go | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/auth/oauth.go b/auth/oauth.go index 714aed099..9a0f33f8a 100644 --- a/auth/oauth.go +++ b/auth/oauth.go @@ -1,23 +1,28 @@ package main import ( - "context" "fmt" "io/ioutil" + "net" "net/http" "net/url" "os" "os/exec" - "time" ) func main() { - port := 3999 // TODO: find available port number state := "TODO" // replace with random unguessable value clientID := os.Getenv("GH_OAUTH_CLIENT_ID") clientSecret := os.Getenv("GH_OAUTH_CLIENT_SECRET") + code := "" + listener, err := net.Listen("tcp", "localhost:0") + if err != nil { + panic(err) + } + port := listener.Addr().(*net.TCPAddr).Port + q := url.Values{} q.Set("client_id", clientID) q.Set("redirect_uri", fmt.Sprintf("http://localhost:%d", port)) @@ -25,24 +30,19 @@ func main() { q.Set("state", state) cmd := exec.Command("open", fmt.Sprintf("https://github.com/login/oauth/authorize?%s", q.Encode())) - err := cmd.Run() + err = cmd.Run() if err != nil { panic(err) } - code := "" - srv := &http.Server{Addr: fmt.Sprintf("localhost:%d", port)} - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { rq := r.URL.Query() code = rq.Get("code") // TODO: rq.Get("state") w.Header().Add("content-type", "text/html") fmt.Fprintf(w, "

You have authenticated GitHub CLI. You may now close this page.

") - time.AfterFunc(10*time.Millisecond, func() { - srv.Shutdown(context.TODO()) - }) - }) - srv.ListenAndServe() + defer listener.Close() + })) resp, err := http.PostForm("https://github.com/login/oauth/access_token", url.Values{