/
login.go
300 lines (252 loc) · 10.1 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
package cli
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/pkg/browser"
"github.com/spf13/cobra"
"github.com/auth0/auth0-cli/internal/ansi"
"github.com/auth0/auth0-cli/internal/auth"
"github.com/auth0/auth0-cli/internal/config"
"github.com/auth0/auth0-cli/internal/keyring"
"github.com/auth0/auth0-cli/internal/prompt"
)
var (
loginTenantDomain = Flag{
Name: "Tenant Domain",
LongForm: "domain",
Help: "Tenant domain of the application when authenticating via client credentials.",
IsRequired: false,
AlwaysPrompt: false,
}
loginClientID = Flag{
Name: "Client ID",
LongForm: "client-id",
Help: "Client ID of the application when authenticating via client credentials.",
IsRequired: false,
AlwaysPrompt: false,
}
loginClientSecret = Flag{
Name: "Client Secret",
LongForm: "client-secret",
Help: "Client secret of the application when authenticating via client credentials.",
IsRequired: false,
AlwaysPrompt: false,
}
loginAdditionalScopes = Flag{
Name: "Additional Scopes",
LongForm: "scopes",
Help: "Additional scopes to request when authenticating via device code flow. By default, only scopes for first-class functions are requested. Primarily useful when using the api command to execute arbitrary Management API requests.",
IsRequired: false,
AlwaysPrompt: false,
}
)
type LoginInputs struct {
Domain string
ClientID string
ClientSecret string
AdditionalScopes []string
}
func (i *LoginInputs) isLoggingInAsAMachine() bool {
return i.ClientID != "" || i.ClientSecret != "" || i.Domain != ""
}
func (i *LoginInputs) isLoggingInWithAdditionalScopes() bool {
return len(i.AdditionalScopes) > 0
}
func loginCmd(cli *cli) *cobra.Command {
var inputs LoginInputs
cmd := &cobra.Command{
Use: "login",
Args: cobra.NoArgs,
Short: "Authenticate the Auth0 CLI",
Long: "Authenticates the Auth0 CLI either as a user using personal credentials or as a machine using client " +
"credentials.\n\nAuthenticating as a user is recommended when working on a personal machine or other " +
"interactive environment; it is not available for Private Cloud users. Authenticating as a machine is " +
"recommended when running on a server or non-interactive environments (ex: CI).",
Example: ` auth0 login
auth0 login --domain <tenant-domain> --client-id <client-id> --client-secret <client-secret>
auth0 login --scopes "read:client_grants,create:client_grants"`,
RunE: func(cmd *cobra.Command, args []string) error {
var selectedLoginType string
const loginAsUser, loginAsMachine = "As a user", "As a machine"
// We want to prompt if we don't pass the following flags:
// --no-input, --scopes, --client-id, --client-secret, --domain.
// Because then the prompt is unnecessary as we know the login type.
shouldPrompt := !inputs.isLoggingInAsAMachine() && !cli.noInput && !inputs.isLoggingInWithAdditionalScopes()
if shouldPrompt {
cli.renderer.Output(
fmt.Sprintf(
"%s\n\n%s\n%s\n\n%s\n%s\n%s\n%s\n\n",
ansi.Bold("✪ Welcome to the Auth0 CLI 🎊"),
"An Auth0 tenant is required to operate this CLI.",
"To create one, visit: https://auth0.com/signup.",
"You may authenticate to your tenant either as a user with personal",
"credentials or as a machine via client credentials. For more",
"information about authenticating the CLI to your tenant, visit",
"the docs: https://auth0.github.io/auth0-cli/auth0_login.html",
),
)
label := "How would you like to authenticate?"
help := fmt.Sprintf(
"%s\n%s\n",
"Authenticating as a user is recommended if performing ad-hoc operations or working locally.",
"Alternatively, authenticating as a machine is recommended for automated workflows (ex:CI).",
)
input := prompt.SelectInput("", label, help, []string{loginAsUser, loginAsMachine}, loginAsUser, shouldPrompt)
if err := prompt.AskOne(input, &selectedLoginType); err != nil {
return handleInputError(err)
}
}
ctx := cmd.Context()
// Allows to skip to user login if either the --no-input or --scopes flag is passed.
shouldLoginAsUser := (cli.noInput && !inputs.isLoggingInAsAMachine()) || inputs.isLoggingInWithAdditionalScopes() || selectedLoginType == loginAsUser
if shouldLoginAsUser {
if _, err := RunLoginAsUser(ctx, cli, inputs.AdditionalScopes); err != nil {
return fmt.Errorf("failed to start the authentication process: %w", err)
}
} else {
if err := RunLoginAsMachine(ctx, inputs, cli, cmd); err != nil {
return err
}
}
cli.tracker.TrackCommandRun(cmd, cli.Config.InstallID)
if len(cli.Config.Tenants) > 1 {
cli.renderer.Infof("%s Switch between authenticated tenants with `auth0 tenants use <tenant>`",
ansi.Faint("Hint:"),
)
}
return nil
},
}
loginTenantDomain.RegisterString(cmd, &inputs.Domain, "")
loginClientID.RegisterString(cmd, &inputs.ClientID, "")
loginClientSecret.RegisterString(cmd, &inputs.ClientSecret, "")
loginAdditionalScopes.RegisterStringSlice(cmd, &inputs.AdditionalScopes, []string{})
cmd.MarkFlagsRequiredTogether("client-id", "client-secret", "domain")
cmd.MarkFlagsMutuallyExclusive("client-id", "scopes")
cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
_ = cmd.Flags().MarkHidden("tenant")
cmd.Parent().HelpFunc()(cmd, args)
})
return cmd
}
// RunLoginAsUser runs the login flow guiding the user through the process
// by showing the login instructions, opening the browser.
func RunLoginAsUser(ctx context.Context, cli *cli, additionalScopes []string) (config.Tenant, error) {
state, err := auth.GetDeviceCode(ctx, http.DefaultClient, additionalScopes)
if err != nil {
return config.Tenant{}, fmt.Errorf("failed to get the device code: %w", err)
}
message := fmt.Sprintf("\n%s\n\n",
"Verify "+ansi.Bold(state.UserCode)+" code in opened browser window to complete authentication.",
)
cli.renderer.Output(message)
if cli.noInput {
message = "Open the following URL in a browser: %s\n"
cli.renderer.Infof(message, ansi.Green(state.VerificationURI))
} else {
message = "%s to open the browser to log in or %s to quit..."
cli.renderer.Infof(message, ansi.Green("Press Enter"), ansi.Red("^C"))
if _, err = fmt.Scanln(); err != nil {
return config.Tenant{}, err
}
if err = browser.OpenURL(state.VerificationURI); err != nil {
message = "Couldn't open the URL, please do it manually: %s."
cli.renderer.Warnf(message, state.VerificationURI)
}
}
var result auth.Result
err = ansi.Spinner("Waiting for the login to complete in the browser", func() error {
result, err = auth.WaitUntilUserLogsIn(ctx, http.DefaultClient, state)
return err
})
if err != nil {
return config.Tenant{}, fmt.Errorf("login error: %w", err)
}
cli.renderer.Newline()
cli.renderer.Infof("Successfully logged in.")
cli.renderer.Infof("Tenant: %s", result.Domain)
cli.renderer.Newline()
tenant := config.Tenant{
Name: result.Tenant,
Domain: result.Domain,
ExpiresAt: result.ExpiresAt,
Scopes: append(auth.RequiredScopes, additionalScopes...),
}
if err := keyring.StoreRefreshToken(result.Domain, result.RefreshToken); err != nil {
cli.renderer.Warnf("Could not store the access token and the refresh token to the keyring: %s", err)
cli.renderer.Warnf("Expect to login again when your access token expires.")
}
if err := keyring.StoreAccessToken(result.Domain, result.AccessToken); err != nil {
// In case we don't have a keyring, we want the
// access token to be saved in the config file.
tenant.AccessToken = result.AccessToken
}
err = cli.Config.AddTenant(tenant)
if err != nil {
return config.Tenant{}, fmt.Errorf("failed to add the tenant to the config: %w", err)
}
cli.tracker.TrackFirstLogin(cli.Config.InstallID)
if cli.Config.DefaultTenant != result.Domain {
message = fmt.Sprintf(
"Your default tenant is %s. Do you want to change it to %s?",
cli.Config.DefaultTenant,
result.Domain,
)
if confirmed := prompt.Confirm(message); !confirmed {
return config.Tenant{}, nil
}
if err := cli.Config.SetDefaultTenant(result.Domain); err != nil {
message = "Failed to set the default tenant, please try 'auth0 tenants use %s' instead: %w"
cli.renderer.Warnf(message, result.Domain, err)
}
}
return tenant, nil
}
// RunLoginAsMachine facilitates the authentication process using client credentials (client ID, client secret).
func RunLoginAsMachine(ctx context.Context, inputs LoginInputs, cli *cli, cmd *cobra.Command) error {
if err := loginTenantDomain.Ask(cmd, &inputs.Domain, nil); err != nil {
return err
}
if err := loginClientID.Ask(cmd, &inputs.ClientID, nil); err != nil {
return err
}
if err := loginClientSecret.AskPassword(cmd, &inputs.ClientSecret); err != nil {
return err
}
token, err := auth.GetAccessTokenFromClientCreds(
ctx,
auth.ClientCredentials{
ClientID: inputs.ClientID,
ClientSecret: inputs.ClientSecret,
Domain: inputs.Domain,
},
)
if err != nil {
return fmt.Errorf("failed to fetch access token using client credentials. \n\nEnsure that the provided client-id, client-secret and domain are correct. \n\nerror: %w", err)
}
tenant := config.Tenant{
Name: strings.Split(inputs.Domain, ".")[0],
Domain: inputs.Domain,
ExpiresAt: token.ExpiresAt,
ClientID: inputs.ClientID,
}
if err = keyring.StoreClientSecret(inputs.Domain, inputs.ClientSecret); err != nil {
cli.renderer.Warnf("Could not store the client secret and the access token to the keyring: %s", err)
cli.renderer.Warnf("Expect to login again when your access token expires.")
}
if err := keyring.StoreAccessToken(inputs.Domain, token.AccessToken); err != nil {
// In case we don't have a keyring, we want the
// access token to be saved in the config file.
tenant.AccessToken = token.AccessToken
}
if err = cli.Config.AddTenant(tenant); err != nil {
return fmt.Errorf("failed to save tenant data: %w", err)
}
cli.renderer.Newline()
cli.renderer.Infof("Successfully logged in.")
cli.renderer.Infof("Tenant: %s", inputs.Domain)
cli.tracker.TrackFirstLogin(cli.Config.InstallID)
return nil
}