2 Copyright 2014 The Kubernetes Authors.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
26 "golang.org/x/crypto/ssh/terminal"
28 clientauth "k8s.io/client-go/tools/auth"
31 // AuthLoaders are used to build clientauth.Info objects.
32 type AuthLoader interface {
33 // LoadAuth takes a path to a config file and can then do anything it needs in order to return a valid clientauth.Info
34 LoadAuth(path string) (*clientauth.Info, error)
37 // default implementation of an AuthLoader
38 type defaultAuthLoader struct{}
40 // LoadAuth for defaultAuthLoader simply delegates to clientauth.LoadFromFile
41 func (*defaultAuthLoader) LoadAuth(path string) (*clientauth.Info, error) {
42 return clientauth.LoadFromFile(path)
45 type PromptingAuthLoader struct {
49 // LoadAuth parses an AuthInfo object from a file path. It prompts user and creates file if it doesn't exist.
50 func (a *PromptingAuthLoader) LoadAuth(path string) (*clientauth.Info, error) {
51 // Prompt for user/pass and write a file if none exists.
52 if _, err := os.Stat(path); os.IsNotExist(err) {
53 authPtr, err := a.Prompt()
58 data, err := json.Marshal(auth)
62 err = ioutil.WriteFile(path, data, 0600)
65 authPtr, err := clientauth.LoadFromFile(path)
72 // Prompt pulls the user and password from a reader
73 func (a *PromptingAuthLoader) Prompt() (*clientauth.Info, error) {
75 auth := &clientauth.Info{}
76 auth.User, err = promptForString("Username", a.reader, true)
80 auth.Password, err = promptForString("Password", nil, false)
87 func promptForString(field string, r io.Reader, show bool) (result string, err error) {
88 fmt.Printf("Please enter %s: ", field)
90 _, err = fmt.Fscan(r, &result)
93 if terminal.IsTerminal(int(os.Stdin.Fd())) {
94 data, err = terminal.ReadPassword(int(os.Stdin.Fd()))
97 return "", fmt.Errorf("error reading input for %s", field)
103 // NewPromptingAuthLoader is an AuthLoader that parses an AuthInfo object from a file path. It prompts user and creates file if it doesn't exist.
104 func NewPromptingAuthLoader(reader io.Reader) *PromptingAuthLoader {
105 return &PromptingAuthLoader{reader}
108 // NewDefaultAuthLoader returns a default implementation of an AuthLoader that only reads from a config file
109 func NewDefaultAuthLoader() AuthLoader {
110 return &defaultAuthLoader{}