forked from cloudfoundry/cli
/
k8s_auth.go
89 lines (71 loc) · 2.51 KB
/
k8s_auth.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
package v7action
import (
"errors"
"fmt"
"sort"
"github.com/LukasHeimann/cloudfoundrycli/v8/api/cloudcontroller/ccv3"
"github.com/LukasHeimann/cloudfoundrycli/v8/api/uaa/constant"
"github.com/LukasHeimann/cloudfoundrycli/v8/cf/configuration/coreconfig"
"github.com/LukasHeimann/cloudfoundrycli/v8/resources"
"github.com/LukasHeimann/cloudfoundrycli/v8/util/configv3"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . KubernetesConfigGetter
type KubernetesConfigGetter interface {
Get() (*clientcmdapi.Config, error)
}
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . WhoAmIer
type WhoAmIer interface {
WhoAmI() (resources.K8sUser, ccv3.Warnings, error)
}
type DefaultKubernetesConfigGetter struct{}
func NewDefaultKubernetesConfigGetter() DefaultKubernetesConfigGetter {
return DefaultKubernetesConfigGetter{}
}
func (c DefaultKubernetesConfigGetter) Get() (*clientcmdapi.Config, error) {
pathOpts := clientcmd.NewDefaultPathOptions()
return pathOpts.GetStartingConfig()
}
type kubernetesAuthActor struct {
config Config
k8sConfigGetter KubernetesConfigGetter
whoAmIer WhoAmIer
}
func NewKubernetesAuthActor(config Config, k8sConfigGetter KubernetesConfigGetter, whoAmIer WhoAmIer) AuthActor {
return &kubernetesAuthActor{
config: config,
k8sConfigGetter: k8sConfigGetter,
whoAmIer: whoAmIer,
}
}
func (actor kubernetesAuthActor) Authenticate(credentials map[string]string, origin string, grantType constant.GrantType) error {
actor.config.SetKubernetesAuthInfo(credentials["k8s-auth-info"])
return nil
}
func (actor kubernetesAuthActor) GetLoginPrompts() (map[string]coreconfig.AuthPrompt, error) {
conf, err := actor.k8sConfigGetter.Get()
if err != nil {
return nil, err
}
if len(conf.AuthInfos) == 0 {
return nil, errors.New("no kubernetes authentication infos configured")
}
var prompts []string
for authInfo := range conf.AuthInfos {
prompts = append(prompts, authInfo)
}
sort.Strings(prompts)
return map[string]coreconfig.AuthPrompt{"k8s-auth-info": {
Type: coreconfig.AuthPromptTypeMenu,
Entries: prompts,
DisplayName: "Choose your Kubernetes authentication info",
}}, nil
}
func (actor kubernetesAuthActor) GetCurrentUser() (configv3.User, error) {
user, _, err := actor.whoAmIer.WhoAmI()
if err != nil {
return configv3.User{}, fmt.Errorf("calling /whoami endpoint failed: %w", err)
}
return configv3.User{Name: user.Name}, nil
}