/
login.go
335 lines (285 loc) · 9.16 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
// Copyright 2022 MongoDB Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package auth
import (
"context"
"errors"
"fmt"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/require"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/flag"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/log"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/prerun"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/telemetry"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/validate"
"github.com/pkg/browser"
"github.com/spf13/cobra"
"go.mongodb.org/atlas/auth"
)
//go:generate mockgen -destination=../../mocks/mock_login.go -package=mocks github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/auth LoginConfig
type LoginConfig interface {
config.SetSaver
AccessTokenSubject() (string, error)
OrgID() string
ProjectID() string
}
var (
ErrProjectIDNotFound = errors.New("project is inaccessible. You either don't have access to this project or the project doesn't exist")
ErrOrgIDNotFound = errors.New("organization is inaccessible. You don't have access to this organization or the organization doesn't exist")
)
type LoginOpts struct {
cli.DefaultSetterOpts
cli.RefresherOpts
AccessToken string
RefreshToken string
IsGov bool
NoBrowser bool
SkipConfig bool
config LoginConfig
}
// SyncWithOAuthAccessProfile returns a function that is synchronizing the oauth settings
// from a login config profile with the provided command opts.
func (opts *LoginOpts) SyncWithOAuthAccessProfile(c LoginConfig) func() error {
return func() error {
opts.config = c
switch {
case opts.IsGov:
opts.Service = config.CloudGovService
default:
opts.Service = config.CloudService
}
opts.config.Set("service", opts.Service)
if opts.AccessToken != "" {
opts.config.Set(config.AccessTokenField, opts.AccessToken)
}
if opts.RefreshToken != "" {
opts.config.Set(config.RefreshTokenField, opts.RefreshToken)
}
if config.ClientID() != "" {
opts.config.Set(config.ClientIDField, config.ClientID())
}
// sync OpsManagerURL from command opts (higher priority)
// and OpsManagerURL from default profile
if opts.OpsManagerURL != "" {
opts.config.Set(config.OpsManagerURLField, opts.OpsManagerURL)
}
if config.OpsManagerURL() != "" {
opts.OpsManagerURL = config.OpsManagerURL()
}
return nil
}
}
func (opts *LoginOpts) LoginRun(ctx context.Context) error {
if err := opts.oauthFlow(ctx); err != nil {
return err
}
// oauth config might have changed,
// re-sync config profile with login opts
if err := opts.SyncWithOAuthAccessProfile(opts.config)(); err != nil {
return err
}
s, err := opts.config.AccessTokenSubject()
if err != nil {
return err
}
if err := opts.checkProfile(ctx); err != nil {
return err
}
if err := opts.config.Save(); err != nil {
return err
}
_, _ = fmt.Fprintf(opts.OutWriter, "Successfully logged in as %s.\n", s)
if opts.SkipConfig {
return nil
}
if err := opts.setUpProfile(ctx); err != nil {
return err
}
if config.Name() != config.DefaultProfile {
_, _ = fmt.Fprintf(opts.OutWriter, "To use this profile, you must set the flag [-%s %s] for every command.\n", flag.ProfileShort, config.Name())
}
return nil
}
func (opts *LoginOpts) checkProfile(ctx context.Context) error {
if err := opts.InitStore(ctx); err != nil {
return err
}
if opts.config.OrgID() != "" && !opts.OrgExists(opts.config.OrgID()) {
opts.config.Set("org_id", "")
}
if opts.config.ProjectID() != "" && !opts.ProjectExists(opts.config.ProjectID()) {
opts.config.Set("project_id", "")
}
return nil
}
func (opts *LoginOpts) setUpProfile(ctx context.Context) error {
if err := opts.InitStore(ctx); err != nil {
return err
}
// Initialize the text to be displayed if users are asked to select orgs or projects
opts.OnMultipleOrgsOrProjects = func() {
if !opts.AskedOrgsOrProjects {
_, _ = fmt.Fprintln(opts.OutWriter, `Select one default organization and one default project.`)
}
}
if opts.config.OrgID() == "" || !opts.OrgExists(opts.config.OrgID()) {
if err := opts.AskOrg(); err != nil {
return err
}
}
opts.SetUpOrg()
if opts.config.ProjectID() == "" || !opts.ProjectExists(opts.config.ProjectID()) {
if err := opts.AskProject(); err != nil {
return err
}
}
opts.SetUpProject()
// Only make references to profile if user was asked about org or projects
if opts.AskedOrgsOrProjects && opts.ProjectID != "" && opts.OrgID != "" {
if !opts.ProjectExists(opts.config.ProjectID()) {
return ErrProjectIDNotFound
}
if !opts.OrgExists(opts.config.OrgID()) {
return ErrOrgIDNotFound
}
_, _ = fmt.Fprintf(opts.OutWriter, `
You have successfully configured your profile.
You can use [%s config set] to change your profile settings later.
`, config.BinName())
}
return opts.config.Save()
}
func (opts *LoginOpts) printAuthInstructions(code *auth.DeviceCode) {
codeDuration := time.Duration(code.ExpiresIn) * time.Second
_, _ = fmt.Fprintf(opts.OutWriter, `
To verify your account, copy your one-time verification code:
`)
userCode := fmt.Sprintf("%s-%s", code.UserCode[0:len(code.UserCode)/2], code.UserCode[len(code.UserCode)/2:])
_, _ = fmt.Fprintln(opts.OutWriter, userCode)
_, _ = fmt.Fprintf(opts.OutWriter, `
Paste the code in the browser when prompted to activate your Atlas CLI. Your code will expire after %.0f minutes.
To continue, go to `,
codeDuration.Minutes(),
)
_, _ = fmt.Fprintln(opts.OutWriter, code.VerificationURI)
}
func (opts *LoginOpts) handleBrowser(uri string) {
if opts.NoBrowser {
return
}
if errBrowser := browser.OpenURL(uri); errBrowser != nil {
_, _ = log.Warningln("There was an issue opening your browser")
}
}
func (opts *LoginOpts) oauthFlow(ctx context.Context) error {
askedToOpenBrowser := false
for {
code, _, err := opts.RequestCode(ctx)
if err != nil {
return err
}
opts.printAuthInstructions(code)
if !askedToOpenBrowser {
opts.handleBrowser(code.VerificationURI)
askedToOpenBrowser = true
}
accessToken, _, err := opts.PollToken(ctx, code)
if retry, errRetry := shouldRetryAuthenticate(err, newRegenerationPrompt()); errRetry != nil {
return errRetry
} else if retry {
continue
}
if err != nil {
return err
}
opts.AccessToken = accessToken.AccessToken
opts.RefreshToken = accessToken.RefreshToken
return nil
}
}
func shouldRetryAuthenticate(err error, p survey.Prompt) (retry bool, errSurvey error) {
if err == nil || !auth.IsTimeoutErr(err) {
return false, nil
}
err = telemetry.TrackAskOne(p, &retry)
return retry, err
}
func newRegenerationPrompt() survey.Prompt {
return &survey.Confirm{
Message: "Your one-time verification code is expired. Would you like to generate a new one?",
Default: true,
}
}
func (opts *LoginOpts) LoginPreRun(ctx context.Context) func() error {
return func() error {
// ignore expired tokens since logging in
if err := opts.RefreshAccessToken(ctx); err != nil {
// clean up any expired or invalid tokens
opts.config.Set(config.AccessTokenField, "")
if !errors.Is(err, cli.ErrInvalidRefreshToken) {
return err
}
}
return nil
}
}
func LoginBuilder() *cobra.Command {
opts := &LoginOpts{}
cmd := &cobra.Command{
Use: "login",
Short: "Authenticate with MongoDB Atlas.",
Example: fmt.Sprintf(` # Log in to your MongoDB Atlas account in interactive mode:
%s auth login
`, config.BinName()),
PreRunE: func(cmd *cobra.Command, _ []string) error {
opts.OutWriter = cmd.OutOrStdout()
defaultProfile := config.Default()
return prerun.ExecuteE(
opts.SyncWithOAuthAccessProfile(defaultProfile),
opts.InitFlow(defaultProfile),
opts.LoginPreRun(cmd.Context()),
validate.NoAPIKeys,
validate.NoAccessToken,
)
},
RunE: func(cmd *cobra.Command, _ []string) error {
return opts.LoginRun(cmd.Context())
},
Args: require.NoArgs,
}
cmd.Flags().BoolVar(&opts.IsGov, "gov", false, "Log in to Atlas for Government.")
cmd.Flags().BoolVar(&opts.NoBrowser, "noBrowser", false, "Don't try to open a browser session.")
cmd.Flags().BoolVar(&opts.SkipConfig, "skipConfig", false, "Skip profile configuration.")
_ = cmd.Flags().MarkDeprecated("skipConfig", "if you configured a profile, the command skips the config step by default.")
return cmd
}
func Builder() *cobra.Command {
cmd := &cobra.Command{
Use: "auth",
Short: "Manage the CLI's authentication state.",
Annotations: map[string]string{
"toc": "true",
},
}
cmd.AddCommand(
LoginBuilder(),
WhoAmIBuilder(),
LogoutBuilder(),
RegisterBuilder(),
)
return cmd
}