generated from brevdev/seed
-
Notifications
You must be signed in to change notification settings - Fork 9
/
login.go
497 lines (438 loc) · 15.4 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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// Package login is for the get command
package login
import (
"bufio"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/brevdev/brev-cli/pkg/auth"
"github.com/brevdev/brev-cli/pkg/cmd/cmderrors"
"github.com/brevdev/brev-cli/pkg/cmd/hello"
"github.com/brevdev/brev-cli/pkg/cmd/importideconfig"
"github.com/brevdev/brev-cli/pkg/entity"
breverrors "github.com/brevdev/brev-cli/pkg/errors"
"github.com/brevdev/brev-cli/pkg/store"
"github.com/brevdev/brev-cli/pkg/terminal"
"github.com/brevdev/brev-cli/pkg/util"
"github.com/fatih/color"
"github.com/hashicorp/go-multierror"
"github.com/spf13/cobra"
)
type LoginOptions struct {
Auth Auth
LoginStore LoginStore
}
type LoginStore interface {
GetCurrentUser() (*entity.User, error)
CreateUser(idToken string) (*entity.User, error)
GetOrganizations(options *store.GetOrganizationsOptions) ([]entity.Organization, error)
GetActiveOrganizationOrDefault() (*entity.Organization, error)
CreateOrganization(req store.CreateOrganizationRequest) (*entity.Organization, error)
GetServerSockFile() string
GetWorkspaces(organizationID string, options *store.GetWorkspacesOptions) ([]entity.Workspace, error)
UpdateUser(userID string, updatedUser *entity.UpdateUser) (*entity.User, error)
hello.HelloStore
importideconfig.ImportIDEConfigStore
UserHomeDir() (string, error)
}
type Auth interface {
Login(skipBrowser bool) (*auth.LoginTokens, error)
LoginWithToken(token string) error
}
// loginStore must be a no prompt store
func NewCmdLogin(t *terminal.Terminal, loginStore LoginStore, auth Auth) *cobra.Command {
opts := LoginOptions{
Auth: auth,
LoginStore: loginStore,
}
var loginToken string
var skipBrowser bool
cmd := &cobra.Command{
Annotations: map[string]string{"housekeeping": ""},
Use: "login",
DisableFlagsInUseLine: true,
Short: "Log into brev",
Long: "Log into brev",
Example: "brev login",
PostRunE: func(cmd *cobra.Command, args []string) error {
shouldWe := hello.ShouldWeRunOnboarding(loginStore)
if shouldWe {
user, err := loginStore.GetCurrentUser()
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = hello.CanWeOnboard(t, user, loginStore)
if err != nil {
return breverrors.WrapAndTrace(err)
}
}
return nil
},
Args: cmderrors.TransformToValidationError(cobra.NoArgs),
RunE: func(cmd *cobra.Command, args []string) error {
err := opts.RunLogin(t, loginToken, skipBrowser)
if err != nil {
// if err is ImportIDEConfigError, log err with sentry but continue
if _, ok := err.(*importideconfig.ImportIDEConfigError); !ok {
return breverrors.WrapAndTrace(err)
}
// todo alert sentry
err2 := RunTasksForUser(t)
if err2 != nil {
err = multierror.Append(err, err2)
}
return breverrors.WrapAndTrace(err)
}
return nil
},
}
cmd.Flags().StringVarP(&loginToken, "token", "", "", "token provided to auto login")
cmd.Flags().BoolVar(&skipBrowser, "skip-browser", false, "print url instead of auto opening browser")
return cmd
}
func (o LoginOptions) checkIfInWorkspace() error {
workspaceID, err := o.LoginStore.GetCurrentWorkspaceID()
if err != nil {
return breverrors.WrapAndTrace(err)
}
if workspaceID != "" {
fmt.Println("can not login to instance")
return breverrors.NewValidationError("can not login to instance")
}
return nil
}
func (o LoginOptions) loginAndGetOrCreateUser(loginToken string, skipBrowser bool) (*entity.User, error) {
if loginToken != "" {
err := o.Auth.LoginWithToken(loginToken)
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
} else {
tokens, err := o.Auth.Login(skipBrowser)
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
_, err = CreateNewUser(o.LoginStore, tokens.IDToken)
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
}
user, err := o.LoginStore.GetCurrentUser()
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
return user, nil
}
func (o LoginOptions) getOrCreateOrg(username string) (*entity.Organization, error) {
org, err := o.LoginStore.GetActiveOrganizationOrDefault()
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
if org == nil {
newOrgName := makeFirstOrgName(username)
fmt.Printf("Creating your first org %s ...\n", newOrgName)
org, err = o.LoginStore.CreateOrganization(store.CreateOrganizationRequest{
Name: newOrgName,
})
if err != nil {
return nil, breverrors.WrapAndTrace(err)
}
fmt.Println("done!")
}
return org, nil
}
func (o LoginOptions) RunLogin(t *terminal.Terminal, loginToken string, skipBrowser bool) error {
err := o.checkIfInWorkspace()
if err != nil {
return breverrors.WrapAndTrace(err)
}
caretType := color.New(color.FgGreen, color.Bold).SprintFunc()
fmt.Print("\n")
fmt.Println(" ", caretType("▸"), " Starting Login")
fmt.Print("\n")
user, err := o.loginAndGetOrCreateUser(loginToken, skipBrowser)
if err != nil {
return breverrors.WrapAndTrace(err)
}
org, err := o.getOrCreateOrg(user.Username)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = o.handleOnboarding(user, t)
if err != nil {
return breverrors.WrapAndTrace(err)
}
err = o.showBreadCrumbs(t, org, user)
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func (o LoginOptions) handleOnboarding(user *entity.User, t *terminal.Terminal) error {
// figure out if we should onboard the user
currentOnboardingStatus, err := user.GetOnboardingData()
if err != nil {
return breverrors.WrapAndTrace(err)
}
newOnboardingStatus := make(map[string]interface{})
// todo make this one api call
// if !currentOnboardingStatus.SSH {
// err = OnboardUserWithSSHKeys(t, user, o.LoginStore, true)
// if err != nil {
// return breverrors.WrapAndTrace(err)
// }
// newOnboardingStatus["SSH"] = true
// }
var ide string
if currentOnboardingStatus.Editor == "" {
// Check IDE requirements
ide = terminal.PromptSelectInput(terminal.PromptSelectContent{
Label: "What is your preferred IDE?",
ErrorMsg: "Error: must choose a preferred IDE",
Items: []string{"VSCode", "Vim", "Emacs"},
})
newOnboardingStatus["editor"] = ide
} else {
ide = currentOnboardingStatus.Editor
}
_, err = OnboardUserWithEditors(t, o.LoginStore, ide)
if err != nil {
return breverrors.WrapAndTrace(err)
}
if !currentOnboardingStatus.UsedCLI {
// by getting this far, we know they have set up the cli
newOnboardingStatus["usedCLI"] = true
}
user, err = o.LoginStore.UpdateUser(user.ID, &entity.UpdateUser{
// username, name, and email are required fields, but we only care about onboarding status
Username: user.Username,
Name: user.Name,
Email: user.Email,
OnboardingData: util.MapAppend(user.OnboardingData, newOnboardingStatus),
})
if err != nil {
return breverrors.WrapAndTrace(err)
}
return nil
}
func getOtherOrg(org *entity.Organization, orgs []entity.Organization) *entity.Organization {
for _, o := range orgs {
if o.ID != org.ID {
return &o
}
}
return nil
}
func RunTasksForUser(t *terminal.Terminal) error {
brevBin, err := os.Executable()
if err != nil {
return breverrors.WrapAndTrace(err)
}
cmd := exec.Command(brevBin, "run-tasks", "-d") // #nosec G204
err = cmd.Run()
if err != nil {
fmt.Print("\n")
t.Vprint(t.Red("tasks failed to run ") + t.Yellow("brev run-tasks -d") + t.Red(" in your terminal."))
return breverrors.WrapAndTrace(err)
}
return nil
}
// returns if the user is indeed new
func CreateNewUser(loginStore LoginStore, idToken string) (bool, error) {
_, err := loginStore.CreateUser(idToken)
if err != nil {
if !(strings.Contains(err.Error(), "duplicate username") || strings.Contains(err.Error(), "duplicate external auth id")) {
// This is a real error
return false, breverrors.WrapAndTrace(err)
}
return false, nil
}
return true, nil
}
func OnboardUserWithSSHKeys(t *terminal.Terminal, user *entity.User, _ LoginStore, firstLoop bool) error {
if firstLoop {
t.Vprint(t.Yellow("\n\nYou must add your SSH key to pull and push from your repos.\n"))
} else {
t.Vprint(t.Red("\n\nYou must add your SSH key to pull and push from your repos.\n"))
}
// SSH Keys
_ = terminal.PromptGetInput(terminal.PromptContent{
Label: "🔒 Click enter to get your secure SSH key:",
ErrorMsg: "error",
AllowEmpty: true,
})
t.Vprintf("\n" + user.PublicKey + "\n\n")
_ = terminal.PromptGetInput(terminal.PromptContent{
Label: "Copy your public key 👆 then hit enter",
ErrorMsg: "error",
AllowEmpty: true,
})
fmt.Print("\n")
t.Vprint(t.Green("Add the key to your git repo provider"))
t.Vprint(t.Green("\tClick here if you use Github 👉 https://github.com/settings/ssh/new\n\n"))
// t.Eprintf(t.Yellow("\n\tClick here for Gitlab: https://gitlab.com/-/profile/keys\n"))
isFin := terminal.PromptSelectInput(terminal.PromptSelectContent{
Label: "Did you finish adding your SSH key?",
Items: []string{"Yes", "No"},
ErrorMsg: "error",
})
if isFin == "Yes" {
return nil
} else {
// t.Vprint(t.Red("\nYou must add your SSH key to pull and push from your repos. "))
err := OnboardUserWithSSHKeys(t, user, nil, false)
if err != nil {
return breverrors.WrapAndTrace(err)
}
}
return nil
}
func OnboardUserWithEditors(t *terminal.Terminal, _ LoginStore, ide string) (string, error) {
if ide == "VSCode" {
_ = 0
} else {
t.Print("To use " + ide + " for your instance. Use the following command to remote into your machine")
t.Print(t.Green("Brev Shell"))
}
return ide, nil
}
func (o LoginOptions) showBreadCrumbs(t *terminal.Terminal, org *entity.Organization, user *entity.User) error {
orgs, err := o.LoginStore.GetOrganizations(nil)
if err != nil {
return breverrors.WrapAndTrace(err)
}
allWorkspaces, err := o.LoginStore.GetWorkspaces(org.ID, &store.GetWorkspacesOptions{})
if err != nil {
return breverrors.WrapAndTrace(err)
}
userWorkspaces := []entity.Workspace{}
for _, w := range allWorkspaces {
if w.CreatedByUserID == user.ID {
userWorkspaces = append(userWorkspaces, w)
}
}
t.Vprintf(t.Green("current organization: ") + t.Yellow(fmt.Sprintf("%s\n", org.Name)))
if len(orgs) > 1 {
otherOrg := getOtherOrg(org, orgs)
t.Vprintf(t.Green("switch organizations:\n"))
t.Vprintf(t.Yellow("\tbrev set %s\n", otherOrg.Name))
}
if len(allWorkspaces) == 0 {
t.Vprintf(t.Green("create an instance:\n"))
t.Vprintf(t.Yellow("\tbrev start https://github.com/brevdev/hello-react\n"))
}
if len(userWorkspaces) == 0 && len(allWorkspaces) > 1 {
t.Vprintf(t.Green("list teammates instances:\n"))
t.Vprintf(t.Yellow("\tbrev ls --all\n"))
t.Vprintf(t.Green("clone a teammate's instance:\n"))
t.Vprintf(t.Yellow(fmt.Sprintf("\tbrev start %s\n", allWorkspaces[0].Name)))
}
if len(userWorkspaces) > 0 {
t.Vprintf(t.Green("list your instances:\n"))
t.Vprintf(t.Yellow("\tbrev ls\n"))
}
return nil
}
func CheckAndInstallGateway(t *terminal.Terminal, store LoginStore) error {
localOS := terminal.PromptSelectInput(terminal.PromptSelectContent{
Label: "Which operating system does your local computer have?",
ErrorMsg: "error",
Items: []string{"Mac OS (Intel)", "Mac OS (M1 Chip)", "Linux"},
})
home, err := store.UserHomeDir()
if err != nil {
return breverrors.WrapAndTrace(err)
}
jetBrainsDirectory, installScript, err := CreateDownloadPathAndInstallScript(localOS, home)
if err != nil {
return breverrors.WrapAndTrace(err)
}
t.Print("Searching for JetBrains Gateway...")
t.Print("")
// Check if Gateway is already installed
gatewayInstalled := IsGatewayInstalled(jetBrainsDirectory)
if gatewayInstalled {
terminal.DisplayGatewayAlreadyInstalledInstructions(t)
return nil
}
// Check if Toolbox is already installed
toolboxInstalled, gatewayInToolboxInstalled := IsToolboxInstalled(jetBrainsDirectory)
if gatewayInToolboxInstalled {
terminal.DisplayGatewayAlreadyInstalledInstructions(t)
return nil
}
if toolboxInstalled {
terminal.DisplayToolboxInstalledInstructions(t)
return nil
}
InstallGateway(installScript, t)
return nil
}
func IsToolboxInstalled(jetBrainsBaseDirectory string) (toolboxInstalled bool, gatewayInToolboxInstalled bool) {
_, err := os.Stat(jetBrainsBaseDirectory + `/Toolbox`)
if !os.IsNotExist(err) {
// Check if Gateway is already installed in Toolbox
_, err = os.Stat(jetBrainsBaseDirectory + `/Toolbox/apps/JetBrainsGateway`)
return true, !os.IsNotExist(err)
}
return false, false
}
func IsGatewayInstalled(jetBrainsBaseDirectory string) bool {
matches, _ := filepath.Glob(jetBrainsBaseDirectory + `/JetBrainsGateway*`)
return len(matches) > 0
}
func InstallGateway(installScript string, t *terminal.Terminal) {
reader := bufio.NewReader(os.Stdin)
t.Print("You will need to install JetBrains Gateway to use JetBrains IDEs.")
t.Print(`Would you like to install JetBrains Gateway? [y/n]: `)
text, _ := reader.ReadString('\n')
if strings.Compare(text, "y") != 1 {
// n
t.Print("")
t.Print(t.Yellow("Click here to install manually: "))
t.Print("https://www.jetbrains.com/remote-development/gateway")
t.Print("")
} else {
// y
spinner := t.NewSpinner()
spinner.Suffix = " Installing JetBrains Gateway..."
spinner.Start()
// #nosec
cmd := exec.Command("/bin/sh", "-c", installScript)
_, err := cmd.Output()
spinner.Stop()
if err != nil {
t.Errprint(err, "Error installing JetBrains Gateway")
t.Print("")
t.Print(t.Yellow("Click here to install manually: "))
t.Print("https://www.jetbrains.com/remote-development/gateway")
t.Print("")
} else {
t.Print("")
t.Print("")
t.Print(t.Yellow("JetBrains Gateway successfully installed!"))
t.Print("")
t.Print("Run " + t.Green("brev jetbrains") + " and then open Gateway to begin.")
t.Print("")
}
}
}
func CreateDownloadPathAndInstallScript(localOS string, homeDirectory string) (jetBrainsDirectory string, installScript string, err error) {
switch localOS {
case "Mac OS (Intel)":
jetBrainsDirectory = homeDirectory + `/Library/Application Support/JetBrains`
installScript = `set -e; echo "Start installation..."; curl "https://data.services.jetbrains.com/products/download?code=GW&platform=macM1&type=eap,rc,release,beta" --output ./gateway.dmg -L; hdiutil attach gateway.dmg; cp -R "/Volumes/JetBrains Gateway/JetBrains Gateway.app" /Applications; hdiutil unmount "/Volumes/JetBrains Gateway"; rm ./gateway.dmg; echo "JetBrains Gateway successfully installed"`
case "Mac OS (M1 Chip)":
jetBrainsDirectory = homeDirectory + `/Library/Application Support/JetBrains`
installScript = `set -e; echo "Start installation..."; curl "https://data.services.jetbrains.com/products/download?code=GW&platform=macM1&type=eap,rc,release,beta" --output ./gateway.dmg -L; hdiutil attach gateway.dmg; cp -R "/Volumes/JetBrains Gateway/JetBrains Gateway.app" /Applications; hdiutil unmount "/Volumes/JetBrains Gateway"; rm ./gateway.dmg; echo "JetBrains Gateway successfully installed"`
case "Linux":
jetBrainsDirectory = homeDirectory + `/.local/share/JetBrains`
installScript = `set -e; echo "Start installation..."; wget --show-progress -qO ./gateway.tar.gz "https://data.services.jetbrains.com/products/download?code=GW&platform=linux&type=eap,rc,release,beta"; GATEWAY_TEMP_DIR=$(mktemp -d); tar -C "$GATEWAY_TEMP_DIR" -xf gateway.tar.gz; rm ./gateway.tar.gz; "$GATEWAY_TEMP_DIR"/*/bin/gateway.sh; rm -r "$GATEWAY_TEMP_DIR"; echo "JetBrains Gateway was successfully installed";`
}
return jetBrainsDirectory, installScript, nil
}
func makeFirstOrgName(username string) string {
return fmt.Sprintf("%s-hq", username)
}