forked from cloudfoundry/cli
/
login.go
318 lines (256 loc) · 7.53 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
package commands
import (
"cf"
"cf/api"
"cf/configuration"
"cf/net"
"cf/requirements"
"cf/terminal"
"github.com/codegangsta/cli"
"strconv"
"strings"
)
const maxLoginTries = 3
const maxChoices = 50
type Login struct {
ui terminal.UI
config *configuration.Configuration
configRepo configuration.ConfigurationRepository
authenticator api.AuthenticationRepository
endpointRepo api.EndpointRepository
orgRepo api.OrganizationRepository
spaceRepo api.SpaceRepository
}
func NewLogin(ui terminal.UI,
configRepo configuration.ConfigurationRepository,
authenticator api.AuthenticationRepository,
endpointRepo api.EndpointRepository,
orgRepo api.OrganizationRepository,
spaceRepo api.SpaceRepository) (cmd Login) {
cmd.ui = ui
cmd.configRepo = configRepo
cmd.config, _ = configRepo.Get()
cmd.authenticator = authenticator
cmd.endpointRepo = endpointRepo
cmd.orgRepo = orgRepo
cmd.spaceRepo = spaceRepo
return
}
func (cmd Login) GetRequirements(reqFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {
return
}
func (cmd Login) Run(c *cli.Context) {
oldUserName := cmd.config.Username()
apiResponse := cmd.setApi(c)
if apiResponse.IsNotSuccessful() {
cmd.ui.Failed("Invalid API endpoint.\n%s", apiResponse.Message)
return
}
apiResponse = cmd.authenticate(c)
if apiResponse.IsNotSuccessful() {
cmd.ui.Failed("Unable to authenticate.")
return
}
userChanged := (cmd.config.Username() != oldUserName && oldUserName != "")
apiResponse = cmd.setOrganization(c, userChanged)
if apiResponse.IsNotSuccessful() {
cmd.ui.Failed(apiResponse.Message)
return
}
apiResponse = cmd.setSpace(c, userChanged)
if apiResponse.IsNotSuccessful() {
cmd.ui.Failed(apiResponse.Message)
return
}
cmd.ui.ShowConfiguration(cmd.config)
return
}
func (cmd Login) setApi(c *cli.Context) (apiResponse net.ApiResponse) {
api := c.String("a")
if api == "" {
api = cmd.config.Target
}
if api == "" {
api = cmd.ui.Ask("API endpoint%s", terminal.PromptColor(">"))
} else {
cmd.ui.Say("API endpoint: %s", terminal.EntityNameColor(api))
}
endpoint, apiResponse := cmd.endpointRepo.UpdateEndpoint(api)
if !strings.HasPrefix(endpoint, "https://") {
cmd.ui.Say(terminal.WarningColor("Warning: Insecure http API endpoint detected: secure https API endpoints are recommended\n"))
}
return
}
func (cmd Login) authenticate(c *cli.Context) (apiResponse net.ApiResponse) {
username := c.String("u")
if username == "" {
username = cmd.ui.Ask("Username%s", terminal.PromptColor(">"))
}
password := c.String("p")
for i := 0; i < maxLoginTries; i++ {
if password == "" || i > 0 {
password = cmd.ui.AskForPassword("Password%s", terminal.PromptColor(">"))
}
cmd.ui.Say("Authenticating...")
apiResponse = cmd.authenticator.Authenticate(username, password)
if apiResponse.IsSuccessful() {
cmd.ui.Ok()
cmd.ui.Say("")
break
}
cmd.ui.Say(apiResponse.Message)
}
return
}
func (cmd Login) setOrganization(c *cli.Context, userChanged bool) (apiResponse net.ApiResponse) {
orgName := c.String("o")
if orgName == "" {
// If the user is changing, clear out the org
if userChanged {
err := cmd.configRepo.SetOrganization(cf.OrganizationFields{})
if err != nil {
apiResponse = net.NewApiResponseWithError("%s", err)
return
}
}
// Reuse org in config
if cmd.config.HasOrganization() && !userChanged {
return
}
stopChan := make(chan bool)
defer close(stopChan)
orgsChan, statusChan := cmd.orgRepo.ListOrgs(stopChan)
availableOrgs := []cf.Organization{}
for orgs := range orgsChan {
availableOrgs = append(availableOrgs, orgs...)
if len(availableOrgs) > maxChoices {
stopChan <- true
break
}
}
apiResponse = <-statusChan
if apiResponse.IsNotSuccessful() {
cmd.ui.Failed("Error finding avilable orgs\n%s", apiResponse.Message)
return
}
// Target only org if possible
if len(availableOrgs) == 1 {
return cmd.targetOrganization(availableOrgs[0])
}
orgName = cmd.promptForOrgName(availableOrgs)
}
// Find org
org, apiResponse := cmd.orgRepo.FindByName(orgName)
if apiResponse.IsNotSuccessful() {
cmd.ui.Failed("Error finding org %s\n%s", terminal.EntityNameColor(orgName), apiResponse.Message)
return
}
return cmd.targetOrganization(org)
}
func (cmd Login) promptForOrgName(orgs []cf.Organization) string {
orgNames := []string{}
for _, org := range orgs {
orgNames = append(orgNames, org.Name)
}
return cmd.promptForName(orgNames, "Select an org:", "Org")
}
func (cmd Login) targetOrganization(org cf.Organization) (apiResponse net.ApiResponse) {
err := cmd.configRepo.SetOrganization(org.OrganizationFields)
if err != nil {
apiResponse = net.NewApiResponseWithMessage("Error setting org %s in config file\n%s",
terminal.EntityNameColor(org.Name),
err.Error(),
)
return
}
cmd.ui.Say("Targeted org %s\n", terminal.EntityNameColor(org.Name))
return
}
func (cmd Login) setSpace(c *cli.Context, userChanged bool) (apiResponse net.ApiResponse) {
spaceName := c.String("s")
if spaceName == "" {
// If user is changing, clear the space
if userChanged {
err := cmd.configRepo.SetSpace(cf.SpaceFields{})
if err != nil {
apiResponse = net.NewApiResponseWithError("%s", err)
return
}
}
// Reuse space in config
if cmd.config.HasSpace() && !userChanged {
return
}
stopChan := make(chan bool)
defer close(stopChan)
spacesChan, statusChan := cmd.spaceRepo.ListSpaces(stopChan)
var availableSpaces []cf.Space
for spaces := range spacesChan {
availableSpaces = append(availableSpaces, spaces...)
if len(availableSpaces) > maxChoices {
stopChan <- true
break
}
}
apiResponse = <-statusChan
if apiResponse.IsNotSuccessful() {
cmd.ui.Failed("Error finding avilable spaces\n%s", apiResponse.Message)
return
}
// Target only space if possible
if len(availableSpaces) == 1 {
return cmd.targetSpace(availableSpaces[0])
}
spaceName = cmd.promptForSpaceName(availableSpaces)
}
// Find space
space, apiResponse := cmd.spaceRepo.FindByName(spaceName)
if apiResponse.IsNotSuccessful() {
cmd.ui.Failed("Error finding space %s\n%s", terminal.EntityNameColor(spaceName), apiResponse.Message)
return
}
return cmd.targetSpace(space)
}
func (cmd Login) promptForSpaceName(spaces []cf.Space) string {
spaceNames := []string{}
for _, space := range spaces {
spaceNames = append(spaceNames, space.Name)
}
return cmd.promptForName(spaceNames, "Select a space:", "Space")
}
func (cmd Login) targetSpace(space cf.Space) (apiResponse net.ApiResponse) {
err := cmd.configRepo.SetSpace(space.SpaceFields)
if err != nil {
apiResponse = net.NewApiResponseWithMessage("Error setting space %s in config file\n%s",
terminal.EntityNameColor(space.Name),
err.Error(),
)
return
}
cmd.ui.Say("Targeted space %s\n", terminal.EntityNameColor(space.Name))
return
}
func (cmd Login) promptForName(names []string, listPrompt, itemPrompt string) string {
nameIndex := 0
var nameString string
for nameIndex < 1 || nameIndex > len(names) {
var err error
// list header
cmd.ui.Say(listPrompt)
// only display list if it is shorter than maxChoices
if len(names) < maxChoices {
for i, name := range names {
cmd.ui.Say("%d. %s", i+1, name)
}
} else {
cmd.ui.Say("There are too many options to display, please type in the name.")
}
nameString = cmd.ui.Ask("%s%s", itemPrompt, terminal.PromptColor(">"))
nameIndex, err = strconv.Atoi(nameString)
if err != nil {
nameIndex = 1
return nameString
}
}
return names[nameIndex-1]
}