forked from openshift/origin
/
login.go
221 lines (175 loc) · 6.72 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
package cmd
import (
"errors"
"fmt"
"io"
"os"
"github.com/spf13/cobra"
kapierrors "github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
kclient "github.com/GoogleCloudPlatform/kubernetes/pkg/client"
kclientcmdapi "github.com/GoogleCloudPlatform/kubernetes/pkg/client/clientcmd/api"
kcmdconfig "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/config"
kcmdutil "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/util"
"github.com/openshift/origin/pkg/cmd/cli/config"
"github.com/openshift/origin/pkg/cmd/flagtypes"
"github.com/openshift/origin/pkg/cmd/templates"
cmdutil "github.com/openshift/origin/pkg/cmd/util"
osclientcmd "github.com/openshift/origin/pkg/cmd/util/clientcmd"
)
// Helper for the login and setup process, gathers all information required for a
// successful login and eventual update of config files.
// Depending on the Reader present it can be interactive, asking for terminal input in
// case of any missing information.
// Notice that some methods mutate this object so it should not be reused. The Config
// provided as a pointer will also mutate (handle new auth tokens, etc).
type LoginOptions struct {
Server string
// flags and printing helpers
Username string
Password string
Project string
// infra
StartingKubeConfig *kclientcmdapi.Config
DefaultNamespace string
Config *kclient.Config
Reader io.Reader
Out io.Writer
// cert data to be used when authenticating
CAFile string
CertFile string
KeyFile string
InsecureTLS bool
Token string
PathOptions *kcmdconfig.PathOptions
}
const (
loginLong = `Log in to an OpenShift server and save config for future use
First-time users of the OpenShift client should run this command to connect to a server,
establish an authenticated session, and save connection to the configuration file. The
default configuration will be saved to your home directory under
".config/openshift/config".
The information required to login -- like username and password, a session token, or
the server details -- can be provided through flags. If not provided, the command will
prompt for user input as needed.`
loginExample = ` // Log in interactively
$ %[1]s login
// Log in to the given server with the given certificate authority file
$ %[1]s login localhost:8443 --certificate-authority=/path/to/cert.crt
// Log in to the given server with the given credentials (will not prompt interactively)
$ %[1]s login localhost:8443 --username=myuser --password=mypass`
)
// NewCmdLogin implements the OpenShift cli login command
func NewCmdLogin(fullName string, f *osclientcmd.Factory, reader io.Reader, out io.Writer) *cobra.Command {
options := &LoginOptions{
Reader: reader,
Out: out,
}
cmds := &cobra.Command{
Use: "login [URL]",
Short: "Log in to an OpenShift server",
Long: loginLong,
Example: fmt.Sprintf(loginExample, fullName),
Run: func(cmd *cobra.Command, args []string) {
if err := options.Complete(f, cmd, args); err != nil {
kcmdutil.CheckErr(err)
}
if err := options.Validate(args, kcmdutil.GetFlagString(cmd, "server")); err != nil {
kcmdutil.CheckErr(err)
}
err := RunLogin(cmd, options)
if kapierrors.IsUnauthorized(err) {
fmt.Fprintln(out, "Login failed (401 Unauthorized)")
if err, isStatusErr := err.(*kapierrors.StatusError); isStatusErr {
if details := err.Status().Details; details != nil {
for _, cause := range details.Causes {
fmt.Fprintln(out, cause.Message)
}
}
}
os.Exit(1)
} else {
kcmdutil.CheckErr(err)
}
},
}
// Login is the only command that can negotiate a session token against the auth server using basic auth
cmds.Flags().StringVarP(&options.Username, "username", "u", "", "Username, will prompt if not provided")
cmds.Flags().StringVarP(&options.Password, "password", "p", "", "Password, will prompt if not provided")
templater := templates.Templater{
UsageTemplate: templates.MainUsageTemplate(),
Exposed: []string{"certificate-authority", "insecure-skip-tls-verify"},
}
cmds.SetUsageFunc(templater.UsageFunc())
cmds.SetHelpTemplate(templates.MainHelpTemplate())
return cmds
}
func (o *LoginOptions) Complete(f *osclientcmd.Factory, cmd *cobra.Command, args []string) error {
kubeconfig, err := f.OpenShiftClientConfig.RawConfig()
o.StartingKubeConfig = &kubeconfig
if err != nil {
if !os.IsNotExist(err) {
return err
}
// build a valid object to use if we failed on a non-existent file
o.StartingKubeConfig = kclientcmdapi.NewConfig()
}
if serverFlag := kcmdutil.GetFlagString(cmd, "server"); len(serverFlag) > 0 {
o.Server = serverFlag
} else if len(args) == 1 {
addr := flagtypes.Addr{Value: "localhost:8443", DefaultScheme: "https", DefaultPort: 8443, AllowPrefix: true}.Default()
if err := addr.Set(args[0]); err != nil {
return err
}
o.Server = addr.String()
} else if len(o.Server) == 0 {
if defaultContext, defaultContextExists := o.StartingKubeConfig.Contexts[o.StartingKubeConfig.CurrentContext]; defaultContextExists {
if cluster, exists := o.StartingKubeConfig.Clusters[defaultContext.Cluster]; exists {
o.Server = cluster.Server
}
}
}
if certFile := kcmdutil.GetFlagString(cmd, "client-certificate"); len(certFile) > 0 {
o.CertFile = certFile
}
if keyFile := kcmdutil.GetFlagString(cmd, "client-key"); len(keyFile) > 0 {
o.KeyFile = keyFile
}
o.CAFile = kcmdutil.GetFlagString(cmd, "certificate-authority")
o.InsecureTLS = kcmdutil.GetFlagBool(cmd, "insecure-skip-tls-verify")
o.Token = kcmdutil.GetFlagString(cmd, "token")
o.DefaultNamespace, _ = f.OpenShiftClientConfig.Namespace()
o.PathOptions = config.NewPathOptions(cmd)
return nil
}
func (o LoginOptions) Validate(args []string, serverFlag string) error {
if len(args) > 1 {
return errors.New("Only the server URL may be specified as an argument")
}
if (len(serverFlag) > 0) && (len(args) == 1) {
return errors.New("--server and passing the server URL as an argument are mutually exclusive")
}
if (len(o.Server) == 0) && !cmdutil.IsTerminal(o.Reader) {
return errors.New("A server URL must be specified")
}
if len(o.Username) > 0 && len(o.Token) > 0 {
return errors.New("--token and --username are mutually exclusive")
}
if o.StartingKubeConfig == nil {
return errors.New("Must have a config file already created")
}
return nil
}
// RunLogin contains all the necessary functionality for the OpenShift cli login command
func RunLogin(cmd *cobra.Command, options *LoginOptions) error {
if err := options.GatherInfo(); err != nil {
return err
}
newFileCreated, err := options.SaveConfig()
if err != nil {
return err
}
if newFileCreated {
fmt.Fprintln(options.Out, "Welcome to OpenShift! See 'osc help' to get started.")
}
return nil
}