-
Notifications
You must be signed in to change notification settings - Fork 72
/
login.go
245 lines (207 loc) · 7.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
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
package login
import (
"context"
"crypto/tls"
"errors"
"net/http"
"net/url"
"github.com/redhat-developer/app-services-cli/pkg/core/auth/login"
"github.com/redhat-developer/app-services-cli/pkg/core/auth/token"
"github.com/redhat-developer/app-services-cli/pkg/core/cmdutil/flagutil"
"github.com/redhat-developer/app-services-cli/pkg/core/config"
"github.com/redhat-developer/app-services-cli/pkg/core/ioutil/icon"
"github.com/redhat-developer/app-services-cli/pkg/core/ioutil/iostreams"
"github.com/redhat-developer/app-services-cli/pkg/core/ioutil/spinner"
"github.com/redhat-developer/app-services-cli/pkg/core/localize"
"github.com/redhat-developer/app-services-cli/pkg/core/logging"
"github.com/redhat-developer/app-services-cli/pkg/shared/connection/kcconnection"
"github.com/redhat-developer/app-services-cli/pkg/shared/factory"
"github.com/redhat-developer/app-services-cli/internal/build"
"golang.org/x/oauth2"
"github.com/spf13/cobra"
)
// When the value of the `--api-gateway` option is one of the keys of this map it will be replaced by the
// corresponding value.
var apiGatewayAliases = map[string]string{
"production": build.ProductionAPIURL,
"prod": build.ProductionAPIURL,
"staging": build.StagingAPIURL,
"stage": build.StagingAPIURL,
}
// When the value of the `--auth-url` option is one of the keys of this map it will be replaced by the
// corresponding value.
var authURLAliases = map[string]string{
"production": build.ProductionAuthURL,
"prod": build.ProductionAuthURL,
"staging": build.ProductionAuthURL,
"stage": build.ProductionAuthURL,
}
type options struct {
Config config.IConfig
Logger logging.Logger
Connection factory.ConnectionFunc
IO *iostreams.IOStreams
localizer localize.Localizer
Context context.Context
url string
authURL string
deprecatedUrl string
clientID string
scopes []string
insecureSkipTLSVerify bool
printURL bool
offlineToken string
}
// NewLoginCmd gets the command that's log the user in
func NewLoginCmd(f *factory.Factory) *cobra.Command {
opts := &options{
Config: f.Config,
Connection: f.Connection,
Logger: f.Logger,
IO: f.IOStreams,
localizer: f.Localizer,
Context: f.Context,
}
cmd := &cobra.Command{
Use: "login",
Short: opts.localizer.MustLocalize("login.cmd.shortDescription"),
Long: opts.localizer.MustLocalize("login.cmd.longDescription", localize.NewEntry("OfflineTokenURL", build.OfflineTokenURL)),
Example: opts.localizer.MustLocalize("login.cmd.example"),
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
if opts.offlineToken != "" && opts.clientID == build.DefaultClientID {
opts.clientID = build.DefaultOfflineTokenClientID
}
if opts.IO.IsSSHSession() && opts.offlineToken == "" {
opts.Logger.Debug(opts.localizer.MustLocalize("login.log.debug.sshLoginDetected", localize.NewEntry("OfflineTokenURL", build.OfflineTokenURL)))
}
return runLogin(opts)
},
}
cmd.Flags().StringVar(&opts.url, "api-gateway", build.ProductionAPIURL, opts.localizer.MustLocalize("login.flag.apiGateway"))
cmd.Flags().BoolVar(&opts.insecureSkipTLSVerify, "insecure", false, opts.localizer.MustLocalize("login.flag.insecure"))
cmd.Flags().StringVar(&opts.clientID, "client-id", build.DefaultClientID, opts.localizer.MustLocalize("login.flag.clientId"))
cmd.Flags().StringVar(&opts.authURL, "auth-url", build.ProductionAuthURL, opts.localizer.MustLocalize("login.flag.authUrl"))
cmd.Flags().StringVar(&opts.deprecatedUrl, "mas-auth-url", "", opts.localizer.MustLocalize("login.flag.masAuthUrl"))
cmd.Flags().BoolVar(&opts.printURL, "print-sso-url", false, opts.localizer.MustLocalize("login.flag.printSsoUrl"))
cmd.Flags().StringArrayVar(&opts.scopes, "scope", kcconnection.DefaultScopes, opts.localizer.MustLocalize("login.flag.scope"))
cmd.Flags().StringVarP(&opts.offlineToken, "token", "t", "", opts.localizer.MustLocalize("login.flag.token", localize.NewEntry("OfflineTokenURL", build.OfflineTokenURL)))
return cmd
}
// nolint:funlen
func runLogin(opts *options) (err error) {
gatewayURL, err := getURLFromAlias(opts.url, apiGatewayAliases, opts.localizer)
if err != nil {
return err
}
authURL, err := getURLFromAlias(opts.authURL, authURLAliases, opts.localizer)
if err != nil {
return err
}
opts.authURL = authURL.String()
// log in to SSO
spinner := spinner.New(opts.IO.ErrOut, opts.localizer)
spinner.SetLocalizedSuffix("login.log.info.loggingIn")
spinner.Start()
if opts.offlineToken == "" {
tr := createTransport(opts.insecureSkipTLSVerify)
httpClient := oauth2.NewClient(opts.Context, nil)
httpClient.Transport = tr
loginExec := &login.AuthorizationCodeGrant{
HTTPClient: httpClient,
Scopes: opts.scopes,
Logger: opts.Logger,
IO: opts.IO,
Config: opts.Config,
ClientID: opts.clientID,
PrintURL: opts.printURL,
Localizer: opts.localizer,
}
ssoCfg := &login.SSOConfig{
AuthURL: authURL,
RedirectPath: build.SSORedirectPath,
}
// Creating a global context with timeout
ctx, cancel := context.WithTimeout(context.Background(), build.DefaultLoginTimeout)
defer cancel()
if err = loginExec.Execute(ctx, ssoCfg, gatewayURL.String()); err != nil {
spinner.Stop()
opts.Logger.Info()
if errors.Is(err, context.DeadlineExceeded) {
return opts.localizer.MustLocalizeError("login.error.context.deadline.exceeded")
}
return err
}
}
if opts.offlineToken != "" {
if err = loginWithOfflineToken(opts); err != nil {
spinner.Stop()
opts.Logger.Info()
return err
}
}
spinner.Stop()
cfg, err := opts.Config.Load()
if err != nil {
return err
}
cfg.APIUrl = gatewayURL.String()
cfg.Insecure = opts.insecureSkipTLSVerify
cfg.ClientID = opts.clientID
cfg.AuthURL = opts.authURL
cfg.Scopes = opts.scopes
if err = opts.Config.Save(cfg); err != nil {
return err
}
username, ok := token.GetUsername(cfg.AccessToken)
opts.Logger.Info()
if !ok {
opts.Logger.Info(icon.SuccessPrefix(), opts.localizer.MustLocalize("login.log.info.loginSuccessNoUsername"))
} else {
opts.Logger.Info(icon.SuccessPrefix(), opts.localizer.MustLocalize("login.log.info.loginSuccess", localize.NewEntry("Username", username)))
}
// debug mode checks this for a version update also.
// so we check if is enabled first so as not to print it twice
if !flagutil.DebugEnabled() {
build.CheckForUpdate(opts.Context, build.Version, opts.Logger, opts.localizer)
}
return nil
}
func loginWithOfflineToken(opts *options) (err error) {
cfg, err := opts.Config.Load()
if err != nil {
return err
}
cfg.Insecure = opts.insecureSkipTLSVerify
cfg.ClientID = opts.clientID
cfg.AuthURL = opts.authURL
cfg.Scopes = opts.scopes
cfg.RefreshToken = opts.offlineToken
if err = opts.Config.Save(cfg); err != nil {
return err
}
return err
}
func createTransport(insecure bool) *http.Transport {
// #nosec 402
return &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure},
}
}
func getURLFromAlias(urlOrAlias string, urlAliasMap map[string]string, localizer localize.Localizer) (u *url.URL, err error) {
// If the URL value is any of the aliases then replace it with the corresponding
// real URL:
unparsedGatewayURL, ok := urlAliasMap[urlOrAlias]
if !ok {
unparsedGatewayURL = urlOrAlias
}
gatewayURL, err := url.ParseRequestURI(unparsedGatewayURL)
if err != nil {
return nil, err
}
if gatewayURL.Scheme != "http" && gatewayURL.Scheme != "https" {
err = localizer.MustLocalizeError("login.error.schemeMissingFromUrl", localize.NewEntry("URL", gatewayURL.String()))
return nil, err
}
return gatewayURL, nil
}