-
Notifications
You must be signed in to change notification settings - Fork 8
/
login.go
109 lines (87 loc) · 2.66 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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package cmd
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/morikuni/aec"
"github.com/pkg/browser"
"github.com/spf13/cobra"
"namespacelabs.dev/foundation/internal/cli/fncobra"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnapi"
"namespacelabs.dev/foundation/internal/gitpod"
)
const baseUrl = "https://login.namespace.so/login/cli"
func NewLoginCmd() *cobra.Command {
var (
readFromEnvVar string
)
cmd := &cobra.Command{
Use: "login",
Short: "Login to use Namespace services (DNS and SSL management, etc).",
Args: cobra.NoArgs,
RunE: fncobra.RunE(func(ctx context.Context, args []string) error {
stdout := console.Stdout(ctx)
var auth *fnapi.UserAuth
if readFromEnvVar != "" {
if nsAuthJson := os.Getenv(readFromEnvVar); nsAuthJson != "" {
auth = &fnapi.UserAuth{}
if err := json.Unmarshal([]byte(nsAuthJson), auth); err != nil {
return err
}
}
}
if auth == nil {
id, exists := os.LookupEnv("nslogintoken")
if !exists {
var err error
id, err = fnapi.StartLogin(ctx)
if err != nil {
return nil
}
fmt.Fprintf(stdout, "%s\n", aec.Bold.Apply("Login to Namespace"))
loginUrl := fmt.Sprintf("%s?id=%s", baseUrl, id)
if openURL(loginUrl) {
fmt.Fprintf(stdout, "Please complete the login flow in your browser.\n\n %s\n", loginUrl)
} else {
fmt.Fprintf(stdout, "In order to login, open the following URL in your browser:\n\n %s\n", loginUrl)
}
} else {
fmt.Fprintf(stdout, "Login pre-approved with a single-use token.\n")
}
tel := fnapi.TelemetryOn(ctx)
ephemeralCliID := ""
if tel != nil {
ephemeralCliID = tel.GetEphemeralCliID(ctx)
}
var err error
auth, err = fnapi.CompleteLogin(ctx, id, ephemeralCliID)
if err != nil {
return err
}
}
username, err := fnapi.StoreUser(ctx, auth)
if err != nil {
return err
}
fmt.Fprintf(stdout, "\nHi %s, you are now logged in, have a nice day.\n", username)
return nil
}),
}
// This flags is used from Gitpod.
cmd.Flags().StringVar(&readFromEnvVar, "read_from_env_var", "", "If true, try reading the auth data as JSON from this environment variable.")
return cmd
}
func openURL(url string) bool {
if gitpod.IsGitpod() {
// This is to avoid using www-browser (lynx) in gitpods.
// TODO is there a way to open a browser here?
return false
}
err := browser.OpenURL(url)
return err == nil
}