]> khamidou — GitHub mirrors - prguy.git/commitdiff
Full flow for github oauth
authorKarim Hamidou <khamidou@gmail.com>
Mon, 17 Jun 2024 04:28:46 +0000 (21:28 -0700)
committerKarim Hamidou <khamidou@gmail.com>
Mon, 17 Jun 2024 04:28:46 +0000 (21:28 -0700)
cmd/prguy/main.go
go.mod
go.sum

index 1b63323324ca6748506c20a981a35da38c0fdc2a..37989e077dc4219b622827bb527b92c545d9e354 100644 (file)
@@ -2,11 +2,21 @@ package main
 
 import (
        "fmt"
+    "os/exec"
+    "time"
+    "errors"
+       "io/ioutil"
+       "net/http"
+       "net/url"
+       "strings"
 
        "github.com/getlantern/systray"
-    "github.com/ncruces/zenity"
+       "github.com/ncruces/zenity"
+       "github.com/skratchdot/open-golang/open"
 )
 
+const GH_CLIENT_ID = "Ov23liJtErJem2rhR36t"
+
 func main() {
        onExit := func() {
        }
@@ -14,6 +24,10 @@ func main() {
        systray.Run(onReady, onExit)
 }
 
+func errorOut(title string, message string) {
+       zenity.Error(message, zenity.Title(title), zenity.ErrorIcon)
+}
+
 func onReady() {
        systray.SetTemplateIcon([]byte("🕴️"), []byte("🕴️"))
        systray.SetTitle("PR Guy")
@@ -22,25 +36,199 @@ func onReady() {
        mQuitOrig := systray.AddMenuItem("Quit", "Quit the app")
 
        go func() {
-        for {
-            select {
-            case <-mQuitOrig.ClickedCh:
-                fmt.Println("Requesting quit")
-                systray.Quit()
-                fmt.Println("Finished quitting")
-            case <-mDoSetup.ClickedCh:
-                fmt.Println("Performing setup")
-                startGithubDeviceAuth()
-            }
-        }
+               for {
+                       select {
+                       case <-mQuitOrig.ClickedCh:
+                               fmt.Println("Requesting quit")
+                               systray.Quit()
+                               fmt.Println("Finished quitting")
+                       case <-mDoSetup.ClickedCh:
+                               fmt.Println("Performing setup")
+                               startGithubDeviceAuth()
+                       }
+               }
        }()
 }
 
 func startGithubDeviceAuth() {
-    res, err := zenity.Entry("Enter new text:", zenity.Title("Add a new entry"))
-    if err != zenity.ErrCanceled {
-        fmt.Println("got an err", err)
-    }
+       formData := url.Values{
+               "client_id": []string{GH_CLIENT_ID},
+               "scope":     []string{"notifications"},
+       }
+
+       encodedForm := formData.Encode()
+       req, err := http.NewRequest("POST",
+               "https://github.com/login/device/code",
+               strings.NewReader(encodedForm))
+       if err != nil {
+               errorOut("Error building request to the Github API", err.Error())
+               return
+       }
+
+       client := &http.Client{}
+       resp, err := client.Do(req)
+       if err != nil {
+               errorOut("Github API error", err.Error())
+               return
+       }
+
+       if resp.StatusCode != 200 {
+               errorOut("Github API error",
+                       fmt.Sprint("Got a '%s'error from the Github API. Please retry in a bit.",
+                       resp.Status)
+               return
+       }
+       defer resp.Body.Close()
+
+       // Read the response body
+       body, err := ioutil.ReadAll(resp.Body)
+       if err != nil {
+               errorOut("Error reading response body", err.Error())
+               return
+       }
+
+       // Parse the form-encoded response
+       fmt.Println("body", string(body))
+       parsedResponse, err := url.ParseQuery(string(body))
+       if err != nil {
+               errorOut("Github API error", err.Error())
+               return
+       }
+
+       device_code, ok := parsedResponse["device_code"]
+       if !ok {
+               errorOut("Missing device code!",
+                       "The Github API did not return us a device code, please retry in a bit.")
+               return
+       }
+
+       user_code, ok := parsedResponse["user_code"]
+       if !ok {
+               errorOut("Missing user code!",
+                       "The Github API did not return us a user code, please retry in a bit.")
+               return
+       }
+
+       verification_uri, ok := parsedResponse["verification_uri"]
+       if !ok {
+               errorOut("Missing verification uri!",
+                       "The Github API did not return us a verification uri, please retry in a bit.")
+               return
+       }
+
+    fmt.Println("user_code", user_code[0])
+    writeToClipboard(user_code[0])
+       zenity.Error("We just copied an authentication code in your clipboard. You will need to give that code to Github",
+               zenity.Title("Github Setup"),
+               zenity.OKLabel("Log into Github"),)
+
+       err = open.Run(verification_uri[0])
+       if err != nil {
+               errorOut("Error opening the browser", err.Error())
+               return
+       }
 
-    fmt.Println("res", res)
+       err = pollGithubDeviceAuth(device_code[0])
+       if err != nil {
+               return
+       }
+}
+
+func pollGithubDeviceAuth(deviceCode string) error {
+       duration := 15 * time.Minute
+       startTime := time.Now()
+       for {
+               // Check if the time has passed
+               if time.Since(startTime) > duration {
+                       errorOut("Timeout", "The device code has expired. Please retry the auth process.")
+                       return errors.New("auth_timeout")
+               }
+
+        fmt.Println("Polling Github API...")
+               formData := url.Values{
+                       "client_id":   []string{GH_CLIENT_ID},
+                       "device_code": []string{deviceCode},
+                       "grant_type":  []string{"urn:ietf:params:oauth:grant-type:device_code"},
+               }
+
+               encodedForm := formData.Encode()
+               req, err := http.NewRequest("POST",
+                       "https://github.com/login/device/code",
+                       strings.NewReader(encodedForm))
+
+               if err != nil {
+                       errorOut("Error building request to the Github API", err.Error())
+                       return errors.New("request_error")
+               }
+
+               client := &http.Client{}
+               resp, err := client.Do(req)
+               if err != nil {
+                       errorOut("Github API error", err.Error())
+                       return errors.New("api_error")
+               }
+
+        if resp.StatusCode == 429 {
+            time.Sleep(15 * time.Second)
+            continue
+        } else if resp.StatusCode != 200 {
+                       errorOut("Github API error",
+                               "Got a "+string(resp.Status)+
+                                       "error from the Github API. "+
+                                       "Please retry in a bit.")
+                       return errors.New("api_error")
+               }
+
+               // Read the response body
+               body, err := ioutil.ReadAll(resp.Body)
+               if err != nil {
+                       errorOut("Error reading response body", err.Error())
+                       return errors.New("response_error")
+               }
+
+               // Parse the form-encoded response
+               parsedResponse, err := url.ParseQuery(string(body))
+               if err != nil {
+                       errorOut("Error parsing Github response", err.Error())
+                       return errors.New("response_error")
+               }
+
+               access_token, ok := parsedResponse["access_token"]
+               if !ok {
+            // sometimes the github API does not error but also does not return the access token.
+            // in this case we just retry.
+            continue
+               }
+
+               scope, ok := parsedResponse["scope"]
+               if !ok {
+                       errorOut("Missing scopes!",
+                               "The Github API did not return us the scopes, please retry in a bit.")
+                       return errors.New("response_error")
+               }
+
+               fmt.Println("access_token", access_token)
+               fmt.Println("scope", scope)
+
+        time.Sleep(5 * time.Second)
+       }
+}
+
+func writeToClipboard(text string) error {
+       copyCmd := exec.Command("pbcopy")
+       in, err := copyCmd.StdinPipe()
+       if err != nil {
+               return err
+       }
+
+       if err := copyCmd.Start(); err != nil {
+               return err
+       }
+       if _, err := in.Write([]byte(text)); err != nil {
+               return err
+       }
+       if err := in.Close(); err != nil {
+               return err
+       }
+       return copyCmd.Wait()
 }
diff --git a/go.mod b/go.mod
index 0caf9bcb088511eb41ce2ff66c0ef0cefbc2f477..fb51890bf6fa46dc76643457deee5927e41edc74 100644 (file)
--- a/go.mod
+++ b/go.mod
@@ -2,6 +2,12 @@ module khamidou.com/prguy
 
 go 1.22.3
 
+require (
+       github.com/getlantern/systray v1.2.2
+       github.com/ncruces/zenity v0.10.12
+       github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966
+)
+
 require (
        github.com/akavel/rsrc v0.10.2 // indirect
        github.com/dchest/jsmin v0.0.0-20220218165748-59f39799265f // indirect
@@ -11,10 +17,8 @@ require (
        github.com/getlantern/hex v0.0.0-20190417191902-c6586a6fe0b7 // indirect
        github.com/getlantern/hidden v0.0.0-20190325191715-f02dbb02be55 // indirect
        github.com/getlantern/ops v0.0.0-20190325191751-d70cb0d6f85f // indirect
-       github.com/getlantern/systray v1.2.2 // indirect
        github.com/go-stack/stack v1.8.0 // indirect
        github.com/josephspurrier/goversioninfo v1.4.0 // indirect
-       github.com/ncruces/zenity v0.10.12 // indirect
        github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect
        github.com/randall77/makefat v0.0.0-20210315173500-7ddd0e42c844 // indirect
        golang.org/x/image v0.15.0 // indirect
diff --git a/go.sum b/go.sum
index d874a5b57455e1c1a3e6ed640557c36f3065101f..93e7a67be911318cb3c230e864c2169e21e82fcb 100644 (file)
--- a/go.sum
+++ b/go.sum
@@ -1,5 +1,6 @@
 github.com/akavel/rsrc v0.10.2 h1:Zxm8V5eI1hW4gGaYsJQUhxpjkENuG91ki8B4zCrvEsw=
 github.com/akavel/rsrc v0.10.2/go.mod h1:uLoCtb9J+EyAqh+26kdrTgmzRBFPGOolLWKpdxkKq+c=
+github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/dchest/jsmin v0.0.0-20220218165748-59f39799265f h1:OGqDDftRTwrvUoL6pOG7rYTmWsTCvyEWFsMjg+HcOaA=
 github.com/dchest/jsmin v0.0.0-20220218165748-59f39799265f/go.mod h1:Dv9D0NUlAsaQcGQZa5kc5mqR9ua72SmA8VXi4cd+cBw=
@@ -27,20 +28,25 @@ github.com/ncruces/zenity v0.10.12 h1:o4SErDa0kQijlqG6W4OYYzO6kA0fGu34uegvJGcMLB
 github.com/ncruces/zenity v0.10.12/go.mod h1:5OZIERViRR2fN0FcJCcisqxI+lYMDGzEDCEwB/+8iao=
 github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
 github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
 github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
 github.com/randall77/makefat v0.0.0-20210315173500-7ddd0e42c844 h1:GranzK4hv1/pqTIhMTXt2X8MmMOuH3hMeUR0o9SP5yc=
 github.com/randall77/makefat v0.0.0-20210315173500-7ddd0e42c844/go.mod h1:T1TLSfyWVBRXVGzWd0o9BI4kfoO9InEgfQe4NV3mLz8=
+github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA=
 github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=
 github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
 github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
 github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
 golang.org/x/image v0.15.0 h1:kOELfmgrmJlw4Cdb7g/QGuB3CvDrXbqEIww/pNtNBm8=
 golang.org/x/image v0.15.0/go.mod h1:HUYqC05R2ZcZ3ejNQsIHQDQiwWM4JBqmm6MKANTp4LE=
 golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
-golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
 golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
 golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
 gopkg.in/Knetic/govaluate.v3 v3.0.0/go.mod h1:csKLBORsPbafmSCGTEh3U7Ozmsuq8ZSIlKk1bcqph0E=
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
 gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=