Skip to content

Commit 246b1d4

Browse files
committed
add login server
1 parent 4bac071 commit 246b1d4

File tree

1 file changed

+45
-6
lines changed

1 file changed

+45
-6
lines changed

cmd/login.go

+45-6
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"bufio"
55
"errors"
66
"fmt"
7+
"io"
8+
"net/http"
79
"os"
810
"regexp"
911
"strings"
@@ -90,13 +92,21 @@ var loginCmd = &cobra.Command{
9092
viper.GetString("base_url") +
9193
"/cli/login")
9294

93-
reader := bufio.NewReader(os.Stdin)
94-
fmt.Print("\nPaste your login code: ")
95-
text, err := reader.ReadString('\n')
95+
inputChan := make(chan string)
9696

97-
if err != nil {
98-
return err
99-
}
97+
go func() {
98+
reader := bufio.NewReader(os.Stdin)
99+
fmt.Print("\nPaste your login code: ")
100+
text, _ := reader.ReadString('\n')
101+
inputChan <- text
102+
}()
103+
104+
go func() {
105+
startHTTPServer(inputChan)
106+
}()
107+
108+
// race the web server against the user's input
109+
text := <-inputChan
100110

101111
re := regexp.MustCompile(`[^A-Za-z0-9_-]`)
102112
text = re.ReplaceAllString(text, "")
@@ -123,6 +133,35 @@ var loginCmd = &cobra.Command{
123133
},
124134
}
125135

136+
func cors(next http.Handler) http.Handler {
137+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
138+
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
139+
w.Header().Set("Access-Control-Allow-Origin", "*")
140+
next.ServeHTTP(w, r)
141+
})
142+
}
143+
func startHTTPServer(inputChan chan string) {
144+
handleSubmit := func(res http.ResponseWriter, req *http.Request) {
145+
code, err := io.ReadAll(req.Body)
146+
if err != nil {
147+
return
148+
}
149+
inputChan <- string(code)
150+
// Clear current line
151+
fmt.Print("\n\033[1A\033[K")
152+
}
153+
154+
handleHealth := func(res http.ResponseWriter, req *http.Request) {
155+
// 200 OK
156+
}
157+
158+
http.Handle("POST /submit", cors(http.HandlerFunc(handleSubmit)))
159+
http.Handle("/health", cors(http.HandlerFunc(handleHealth)))
160+
161+
// if we fail, oh well. we fall back to entering the code
162+
_ = http.ListenAndServe("localhost:9417", nil)
163+
}
164+
126165
func init() {
127166
rootCmd.AddCommand(loginCmd)
128167
}

0 commit comments

Comments
 (0)