-
Notifications
You must be signed in to change notification settings - Fork 240
/
auth.go
294 lines (232 loc) · 6.99 KB
/
auth.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package cmd
import (
"fmt"
"os"
"os/exec"
"time"
"github.com/superfly/flyctl/cmdctx"
"github.com/pkg/errors"
"github.com/superfly/flyctl/docstrings"
"github.com/superfly/flyctl/internal/client"
"github.com/AlecAivazis/survey/v2"
"github.com/briandowns/spinner"
"github.com/logrusorgru/aurora"
"github.com/skratchdot/open-golang/open"
"github.com/spf13/viper"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/flyctl"
"github.com/superfly/flyctl/terminal"
)
func newAuthCommand() *Command {
authStrings := docstrings.Get("auth")
cmd := BuildCommandKS(nil, nil, authStrings, os.Stdout)
authWhoamiStrings := docstrings.Get("auth.whoami")
BuildCommand(cmd, runWhoami, authWhoamiStrings.Usage, authWhoamiStrings.Short, authWhoamiStrings.Long, os.Stdout, requireSession)
authTokenStrings := docstrings.Get("auth.token")
BuildCommand(cmd, runAuthToken, authTokenStrings.Usage, authTokenStrings.Short, authTokenStrings.Long, os.Stdout, requireSession)
authLoginStrings := docstrings.Get("auth.login")
login := BuildCommand(cmd, runLogin, authLoginStrings.Usage, authLoginStrings.Short, authLoginStrings.Long, os.Stdout)
authDockerStrings := docstrings.Get("auth.docker")
BuildCommand(cmd, runAuthDocker, authDockerStrings.Usage, authDockerStrings.Short, authDockerStrings.Long, os.Stdout)
// TODO: Move flag descriptions into the docStrings
login.AddBoolFlag(BoolFlagOpts{
Name: "interactive",
Shorthand: "i",
Description: "Log in with an email and password interactively",
})
login.AddStringFlag(StringFlagOpts{
Name: "email",
Description: "Login email",
})
login.AddStringFlag(StringFlagOpts{
Name: "password",
Description: "Login password",
})
login.AddStringFlag(StringFlagOpts{
Name: "otp",
Description: "One time password",
})
authLogoutStrings := docstrings.Get("auth.logout")
BuildCommand(cmd, runLogout, authLogoutStrings.Usage, authLogoutStrings.Short, authLogoutStrings.Long, os.Stdout, requireSession)
authSignupStrings := docstrings.Get("auth.signup")
BuildCommand(cmd, runSignup, authSignupStrings.Usage, authSignupStrings.Short, authSignupStrings.Long, os.Stdout)
return cmd
}
func runWhoami(ctx *cmdctx.CmdContext) error {
user, err := ctx.Client.API().GetCurrentUser()
if err != nil {
return err
}
fmt.Printf("Current user: %s\n", user.Email)
return nil
}
func runLogin(ctx *cmdctx.CmdContext) error {
if ctx.Config.GetBool("interactive") {
return runInteractiveLogin(ctx)
}
if val, _ := ctx.Config.GetString("email"); val != "" {
return runInteractiveLogin(ctx)
}
if val, _ := ctx.Config.GetString("password"); val != "" {
return runInteractiveLogin(ctx)
}
if val, _ := ctx.Config.GetString("otp"); val != "" {
return runInteractiveLogin(ctx)
}
return runWebLogin(ctx, false)
}
func runSignup(ctx *cmdctx.CmdContext) error {
return runWebLogin(ctx, true)
}
func runWebLogin(ctx *cmdctx.CmdContext, signup bool) error {
name, _ := os.Hostname()
cliAuth, err := api.StartCLISessionWebAuth(name, signup)
if err != nil {
return err
}
//fmt.Fprintln(ctx.Out, "Opening browser to url", aurora.Bold(cliAuth.AuthURL))
if err := open.Run(cliAuth.AuthURL); err != nil {
terminal.Error("Error opening browser. Copy the url " + cliAuth.AuthURL + " into a browser and continue")
}
select {
case <-time.After(15 * time.Minute):
return errors.New("Login expired, please try again")
case cliAuth = <-waitForCLISession(cliAuth.ID):
}
if cliAuth.AccessToken == "" {
return errors.New("Unable to log in, please try again")
}
viper.Set(flyctl.ConfigAPIToken, cliAuth.AccessToken)
if err := flyctl.SaveConfig(); err != nil {
return err
}
if !ctx.Client.InitApi() {
return client.ErrNoAuthToken
}
user, err := ctx.Client.API().GetCurrentUser()
if err != nil {
return err
}
fmt.Println("Successfully logged in as", aurora.Bold(user.Email))
return nil
}
func waitForCLISession(id string) <-chan api.CLISessionAuth {
done := make(chan api.CLISessionAuth)
go func() {
s := spinner.New(spinner.CharSets[11], 100*time.Millisecond)
s.Writer = os.Stderr
s.Prefix = "Waiting for session..."
s.FinalMSG = "Waiting for session...Done\n"
s.Start()
defer s.Stop()
for {
time.Sleep(1 * time.Second)
cliAuth, _ := api.GetAccessTokenForCLISession(id)
if cliAuth.AccessToken != "" {
done <- cliAuth
break
}
}
}()
return done
}
func runInteractiveLogin(ctx *cmdctx.CmdContext) error {
email, _ := ctx.Config.GetString("email")
if email == "" {
prompt := &survey.Input{
Message: "Email:",
}
if err := survey.AskOne(prompt, &email, survey.WithValidator(survey.Required)); err != nil {
if isInterrupt(err) {
return nil
}
}
}
password, _ := ctx.Config.GetString("password")
if password == "" {
prompt := &survey.Password{
Message: "Password:",
}
if err := survey.AskOne(prompt, &password, survey.WithValidator(survey.Required)); err != nil {
if isInterrupt(err) {
return nil
}
}
}
otp, _ := ctx.Config.GetString("otp")
if otp == "" {
prompt := &survey.Password{
Message: "One Time Password (if any):",
}
if err := survey.AskOne(prompt, &otp); err != nil {
if isInterrupt(err) {
return nil
}
}
}
accessToken, err := api.GetAccessToken(email, password, otp)
if err != nil {
return err
}
viper.Set(flyctl.ConfigAPIToken, accessToken)
return flyctl.SaveConfig()
}
func runLogout(ctx *cmdctx.CmdContext) error {
viper.Set(flyctl.ConfigAPIToken, "")
if err := flyctl.SaveConfig(); err != nil {
return err
}
fmt.Println("Session removed")
// Microaudit env vars
_, ok := os.LookupEnv("FLY_API_TOKEN")
if ok {
ctx.Status("auth", cmdctx.SWARN, "FLY_API_TOKEN is set in your environment. Don't forget to remove it.")
}
_, ok = os.LookupEnv("FLY_ACCESS_TOKEN")
if ok {
ctx.Status("auth", cmdctx.SWARN, "FLY_ACCESS_TOKEN is set in your environment. Don't forget to remove it.")
}
return nil
}
func runAuthToken(ctx *cmdctx.CmdContext) error {
token := flyctl.GetAPIToken()
if ctx.OutputJSON() {
ctx.WriteJSON(map[string]string{"flyctlAuthToken": token})
return nil
}
fmt.Fprintln(ctx.Out, token)
return nil
}
func runAuthDocker(ctx *cmdctx.CmdContext) error {
cc := createCancellableContext()
binary, err := exec.LookPath("docker")
if err != nil {
return errors.Wrap(err, "docker cli not found - make sure it's installed and try again")
}
token := flyctl.GetAPIToken()
cmd := exec.CommandContext(cc, binary, "login", "--username=x", "--password-stdin", "registry.fly.io")
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
go func() {
defer stdin.Close()
fmt.Fprint(stdin, token)
}()
if err := cmd.Wait(); err != nil {
return err
}
if !cmd.ProcessState.Success() {
output, err := cmd.CombinedOutput()
if err != nil {
return err
}
fmt.Println(output)
return errors.New("error authenticating with registry.fly.io")
}
fmt.Println("Authentication successful. You can now tag and push images to registry.fly.io/{your-app}")
return nil
}