/
login.go
86 lines (70 loc) · 1.63 KB
/
login.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package command
import (
"net/http"
"github.com/common-fate/clio"
"github.com/common-fate/pdk/pkg/cliauth"
"github.com/common-fate/pdk/pkg/tokenstore"
"github.com/pkg/browser"
"github.com/urfave/cli/v2"
"golang.org/x/sync/errgroup"
)
var Login = cli.Command{
Name: "login",
Usage: "Login to Common Fate Provider Registry",
Flags: []cli.Flag{},
Action: func(c *cli.Context) error {
ctx := c.Context
authResponse := make(chan cliauth.Response)
authServer := cliauth.Server{
Response: authResponse,
}
server := &http.Server{
Addr: ":8848",
Handler: authServer.Handler(),
}
var g errgroup.Group
// run the auth server on localhost
g.Go(func() error {
clio.Debugw("starting HTTP server", "address", server.Addr)
if err := server.ListenAndServe(); err != http.ErrServerClosed {
return err
}
clio.Debugw("auth server closed")
return nil
})
// open the browser and read the token
g.Go(func() error {
url := "http://localhost:8848/oauth/login"
clio.Infof("Opening your web browser to: %s", url)
err := browser.OpenURL(url)
if err != nil {
clio.Errorf("error opening browser: %s", err)
}
return nil
})
// read the returned ID token from Cognito
g.Go(func() error {
res := <-authResponse
err := server.Shutdown(ctx)
if err != nil {
return err
}
// check that the auth flow didn't error out
if res.Err != nil {
return err
}
ts := tokenstore.New()
err = ts.Save(res.Token)
if err != nil {
return err
}
clio.Successf("logged in")
return nil
})
err := g.Wait()
if err != nil {
return err
}
return nil
},
}