本文整理汇总了Golang中github.com/openshift/origin/pkg/cmd/util/tokencmd.RequestToken函数的典型用法代码示例。如果您正苦于以下问题:Golang RequestToken函数的具体用法?Golang RequestToken怎么用?Golang RequestToken使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了RequestToken函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestCLIGetToken
func TestCLIGetToken(t *testing.T) {
testutil.RequireEtcd(t)
_, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI()
checkErr(t, err)
clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
checkErr(t, err)
anonymousConfig := clientcmd.AnonymousClientConfig(clusterAdminClientConfig)
reader := bytes.NewBufferString("user\npass")
accessToken, err := tokencmd.RequestToken(&anonymousConfig, reader, "", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if len(accessToken) == 0 {
t.Error("Expected accessToken, but did not get one")
}
clientConfig := clientcmd.AnonymousClientConfig(clusterAdminClientConfig)
clientConfig.BearerToken = accessToken
osClient, err := client.New(&clientConfig)
checkErr(t, err)
user, err := osClient.Users().Get("~")
checkErr(t, err)
if user.Name != "user" {
t.Errorf("expected %v, got %v", "user", user.Name)
}
}
示例2: TestUnprivilegedNewProject
func TestUnprivilegedNewProject(t *testing.T) {
_, clusterAdminKubeConfig, err := testserver.StartTestMaster()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
valerieClientConfig := *clusterAdminClientConfig
valerieClientConfig.Username = ""
valerieClientConfig.Password = ""
valerieClientConfig.BearerToken = ""
valerieClientConfig.CertFile = ""
valerieClientConfig.KeyFile = ""
valerieClientConfig.CertData = nil
valerieClientConfig.KeyData = nil
accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
valerieClientConfig.BearerToken = accessToken
valerieOpenshiftClient, err := client.New(&valerieClientConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// confirm that we have access to request the project
allowed, err := valerieOpenshiftClient.ProjectRequests().List(labels.Everything(), fields.Everything())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if allowed.Status != unversioned.StatusSuccess {
t.Fatalf("expected %v, got %v", unversioned.StatusSuccess, allowed.Status)
}
requestProject := oc.NewProjectOptions{
ProjectName: "new-project",
DisplayName: "display name here",
Description: "the special description",
Client: valerieOpenshiftClient,
Out: ioutil.Discard,
}
if err := requestProject.Run(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
waitForProject(t, valerieOpenshiftClient, "new-project", 5*time.Second, 10)
if err := requestProject.Run(); !kapierrors.IsAlreadyExists(err) {
t.Fatalf("expected an already exists error, but got %v", err)
}
}
示例3: TestUnprivilegedNewProjectDenied
func TestUnprivilegedNewProjectDenied(t *testing.T) {
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
_, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
role, err := clusterAdminClient.ClusterRoles().Get(bootstrappolicy.SelfProvisionerRoleName)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
role.Rules = []authorizationapi.PolicyRule{}
if _, err := clusterAdminClient.ClusterRoles().Update(role); err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
valerieClientConfig := *clusterAdminClientConfig
valerieClientConfig.Username = ""
valerieClientConfig.Password = ""
valerieClientConfig.BearerToken = ""
valerieClientConfig.CertFile = ""
valerieClientConfig.KeyFile = ""
valerieClientConfig.CertData = nil
valerieClientConfig.KeyData = nil
accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
valerieClientConfig.BearerToken = accessToken
valerieOpenshiftClient, err := client.New(&valerieClientConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := testutil.WaitForClusterPolicyUpdate(valerieOpenshiftClient, "create", projectapi.Resource("projectrequests"), false); err != nil {
t.Fatalf("unexpected error: %v", err)
}
// confirm that we have access to request the project
_, err = valerieOpenshiftClient.ProjectRequests().List(kapi.ListOptions{})
if err == nil {
t.Fatalf("expected error: %v", err)
}
expectedError := `You may not request a new project via this API.`
if (err != nil) && (err.Error() != expectedError) {
t.Fatalf("expected\n\t%v\ngot\n\t%v", expectedError, err.Error())
}
}
示例4: GetClientForUser
func GetClientForUser(clientConfig kclient.Config, username string) (*client.Client, *kclient.Client, *kclient.Config, error) {
token, err := tokencmd.RequestToken(&clientConfig, nil, username, "password")
if err != nil {
return nil, nil, nil, err
}
userClientConfig := clientConfig
userClientConfig.BearerToken = token
userClientConfig.Username = ""
userClientConfig.Password = ""
userClientConfig.TLSClientConfig.CertFile = ""
userClientConfig.TLSClientConfig.KeyFile = ""
userClientConfig.TLSClientConfig.CertData = nil
userClientConfig.TLSClientConfig.KeyData = nil
kubeClient, err := kclient.New(&userClientConfig)
if err != nil {
return nil, nil, nil, err
}
osClient, err := client.New(&userClientConfig)
if err != nil {
return nil, nil, nil, err
}
return osClient, kubeClient, &userClientConfig, nil
}
示例5: TestBootstrapPolicySelfSubjectAccessReviews
func TestBootstrapPolicySelfSubjectAccessReviews(t *testing.T) {
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
_, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
valerieClientConfig := *clusterAdminClientConfig
valerieClientConfig.Username = ""
valerieClientConfig.Password = ""
valerieClientConfig.BearerToken = ""
valerieClientConfig.CertFile = ""
valerieClientConfig.KeyFile = ""
valerieClientConfig.CertData = nil
valerieClientConfig.KeyData = nil
accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
valerieClientConfig.BearerToken = accessToken
valerieOpenshiftClient, err := client.New(&valerieClientConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// can I get a subjectaccessreview on myself even if I have no rights to do it generally
askCanICreatePolicyBindings := &authorizationapi.LocalSubjectAccessReview{
Action: authorizationapi.Action{Verb: "create", Resource: "policybindings"},
}
subjectAccessReviewTest{
localInterface: valerieOpenshiftClient.LocalSubjectAccessReviews("openshift"),
localReview: askCanICreatePolicyBindings,
response: authorizationapi.SubjectAccessReviewResponse{
Allowed: false,
Reason: `User "valerie" cannot create policybindings in project "openshift"`,
Namespace: "openshift",
},
}.run(t)
// I shouldn't be allowed to ask whether someone else can perform an action
askCanClusterAdminsCreateProject := &authorizationapi.LocalSubjectAccessReview{
Groups: sets.NewString("system:cluster-admins"),
Action: authorizationapi.Action{Verb: "create", Resource: "projects"},
}
subjectAccessReviewTest{
localInterface: valerieOpenshiftClient.LocalSubjectAccessReviews("openshift"),
localReview: askCanClusterAdminsCreateProject,
err: `User "valerie" cannot create localsubjectaccessreviews in project "openshift"`,
}.run(t)
}
示例6: TestBootstrapPolicyAuthenticatedUsersAgainstOpenshiftNamespace
func TestBootstrapPolicyAuthenticatedUsersAgainstOpenshiftNamespace(t *testing.T) {
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
_, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
valerieClientConfig := *clusterAdminClientConfig
valerieClientConfig.Username = ""
valerieClientConfig.Password = ""
valerieClientConfig.BearerToken = ""
valerieClientConfig.CertFile = ""
valerieClientConfig.KeyFile = ""
valerieClientConfig.CertData = nil
valerieClientConfig.KeyData = nil
accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
valerieClientConfig.BearerToken = accessToken
valerieOpenshiftClient, err := client.New(&valerieClientConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
openshiftSharedResourcesNamespace := "openshift"
if _, err := valerieOpenshiftClient.Templates(openshiftSharedResourcesNamespace).List(kapi.ListOptions{}); err != nil {
t.Errorf("unexpected error: %v", err)
}
if _, err := valerieOpenshiftClient.Templates(kapi.NamespaceDefault).List(kapi.ListOptions{}); err == nil || !kapierror.IsForbidden(err) {
t.Errorf("unexpected error: %v", err)
}
if _, err := valerieOpenshiftClient.ImageStreams(openshiftSharedResourcesNamespace).List(kapi.ListOptions{}); err != nil {
t.Errorf("unexpected error: %v", err)
}
if _, err := valerieOpenshiftClient.ImageStreams(kapi.NamespaceDefault).List(kapi.ListOptions{}); err == nil || !kapierror.IsForbidden(err) {
t.Errorf("unexpected error: %v", err)
}
if _, err := valerieOpenshiftClient.ImageStreamTags(openshiftSharedResourcesNamespace).Get("name", "tag"); !kapierror.IsNotFound(err) {
t.Errorf("unexpected error: %v", err)
}
if _, err := valerieOpenshiftClient.ImageStreamTags(kapi.NamespaceDefault).Get("name", "tag"); err == nil || !kapierror.IsForbidden(err) {
t.Errorf("unexpected error: %v", err)
}
}
示例7: TestOAuthDisabled
func TestOAuthDisabled(t *testing.T) {
testutil.RequireEtcd(t)
defer testutil.DumpEtcdOnFailure(t)
// Build master config
masterOptions, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Disable OAuth
masterOptions.OAuthConfig = nil
// Start server
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
client, err := testutil.GetClusterAdminKubeClient(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Make sure cert auth still works
namespaces, err := client.Namespaces().List(kapi.ListOptions{})
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
if len(namespaces.Items) == 0 {
t.Errorf("Expected namespaces, got none")
}
// Use the server and CA info
anonConfig := restclient.Config{}
anonConfig.Host = clientConfig.Host
anonConfig.CAFile = clientConfig.CAFile
anonConfig.CAData = clientConfig.CAData
// Make sure we can't authenticate using OAuth
if _, err := tokencmd.RequestToken(&anonConfig, nil, "username", "password"); err == nil {
t.Error("Expected error, got none")
}
}
示例8: NewCmdRequestToken
func NewCmdRequestToken(f *clientcmd.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "request-token",
Short: "Request an access token",
Long: `Request an access token`,
Run: func(cmd *cobra.Command, args []string) {
clientCfg, err := f.OpenShiftClientConfig.ClientConfig()
util.CheckErr(err)
accessToken, err := tokencmd.RequestToken(clientCfg, os.Stdin, "", "")
util.CheckErr(err)
fmt.Printf("%v\n", string(accessToken))
},
}
return cmd
}
示例9: GetClientForUser
func GetClientForUser(clientConfig kclient.Config, username string) (*client.Client, *kclient.Client, *kclient.Config, error) {
token, err := tokencmd.RequestToken(&clientConfig, nil, username, "password")
if err != nil {
return nil, nil, nil, err
}
userClientConfig := clientcmd.AnonymousClientConfig(clientConfig)
userClientConfig.BearerToken = token
kubeClient, err := kclient.New(&userClientConfig)
if err != nil {
return nil, nil, nil, err
}
osClient, err := client.New(&userClientConfig)
if err != nil {
return nil, nil, nil, err
}
return osClient, kubeClient, &userClientConfig, nil
}
示例10: GetClientForUser
// TODO internalclientset: get rid of oldClient after next rebase
func GetClientForUser(clientConfig restclient.Config, username string) (*client.Client, *kclientset.Clientset, *restclient.Config, error) {
token, err := tokencmd.RequestToken(&clientConfig, nil, username, "password")
if err != nil {
return nil, nil, nil, err
}
userClientConfig := clientcmd.AnonymousClientConfig(&clientConfig)
userClientConfig.BearerToken = token
kubeClient, err := kclient.New(&userClientConfig)
if err != nil {
return nil, nil, nil, err
}
kubeClientset := adapter.FromUnversionedClient(kubeClient)
osClient, err := client.New(&userClientConfig)
if err != nil {
return nil, nil, nil, err
}
return osClient, kubeClientset, &userClientConfig, nil
}
示例11: TestCLIGetToken
func TestCLIGetToken(t *testing.T) {
testutil.DeleteAllEtcdKeys()
// setup
etcdClient := testutil.NewEtcdClient()
etcdHelper, _ := master.NewEtcdStorage(etcdClient, latest.InterfacesFor, latest.Version, etcdtest.PathPrefix())
accessTokenStorage := accesstokenetcd.NewREST(etcdHelper)
accessTokenRegistry := accesstokenregistry.NewRegistry(accessTokenStorage)
authorizeTokenStorage := authorizetokenetcd.NewREST(etcdHelper)
authorizeTokenRegistry := authorizetokenregistry.NewRegistry(authorizeTokenStorage)
clientStorage := clientetcd.NewREST(etcdHelper)
clientRegistry := clientregistry.NewRegistry(clientStorage)
clientAuthStorage := clientauthetcd.NewREST(etcdHelper)
clientAuthRegistry := clientauthregistry.NewRegistry(clientAuthStorage)
userStorage := useretcd.NewREST(etcdHelper)
userRegistry := userregistry.NewRegistry(userStorage)
identityStorage := identityetcd.NewREST(etcdHelper)
identityRegistry := identityregistry.NewRegistry(identityStorage)
identityMapper := identitymapper.NewAlwaysCreateUserIdentityToUserMapper(identityRegistry, userRegistry)
authRequestHandler := basicauthrequest.NewBasicAuthAuthentication(allowanypassword.New("get-token-test", identityMapper), true)
authHandler := oauthhandlers.NewUnionAuthenticationHandler(
map[string]oauthhandlers.AuthenticationChallenger{"login": passwordchallenger.NewBasicAuthChallenger("openshift")}, nil, nil)
storage := registrystorage.New(accessTokenRegistry, authorizeTokenRegistry, clientRegistry, oauthregistry.NewUserConversion())
config := osinserver.NewDefaultServerConfig()
grantChecker := oauthregistry.NewClientAuthorizationGrantChecker(clientAuthRegistry)
grantHandler := oauthhandlers.NewAutoGrant()
server := osinserver.New(
config,
storage,
osinserver.AuthorizeHandlers{
oauthhandlers.NewAuthorizeAuthenticator(
authRequestHandler,
authHandler,
oauthhandlers.EmptyError{},
),
oauthhandlers.NewGrantCheck(
grantChecker,
grantHandler,
oauthhandlers.EmptyError{},
),
},
osinserver.AccessHandlers{
oauthhandlers.NewDenyAccessAuthenticator(),
},
osinserver.NewDefaultErrorHandler(),
)
mux := http.NewServeMux()
server.Install(mux, origin.OpenShiftOAuthAPIPrefix)
oauthServer := httptest.NewServer(http.Handler(mux))
defer oauthServer.Close()
t.Logf("oauth server is on %v\n", oauthServer.URL)
// create the default oauth clients with redirects to our server
origin.CreateOrUpdateDefaultOAuthClients(oauthServer.URL, []string{oauthServer.URL}, clientRegistry)
flags := pflag.NewFlagSet("test-flags", pflag.ContinueOnError)
clientCfg := clientcmd.NewConfig()
clientCfg.Bind(flags)
flags.Parse(strings.Split("--master="+oauthServer.URL, " "))
reader := bytes.NewBufferString("user\npass")
accessToken, err := tokencmd.RequestToken(clientCfg.OpenShiftConfig(), reader, "", "")
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if len(accessToken) == 0 {
t.Error("Expected accessToken, but did not get one")
}
// lets see if this access token is any good
token, err := accessTokenRegistry.GetAccessToken(kapi.NewContext(), accessToken)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if token.UserName != "user" {
t.Errorf("Expected token for \"user\", but got: %#v", token)
}
}
示例12: TestHTPasswd
func TestHTPasswd(t *testing.T) {
htpasswdFile, err := ioutil.TempFile("", "test.htpasswd")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer os.Remove(htpasswdFile.Name())
masterOptions, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
masterOptions.OAuthConfig.IdentityProviders[0] = configapi.IdentityProvider{
Name: "htpasswd",
UseAsChallenger: true,
UseAsLogin: true,
Provider: runtime.EmbeddedObject{
Object: &configapi.HTPasswdPasswordIdentityProvider{
File: htpasswdFile.Name(),
},
},
}
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Use the server and CA info
anonConfig := kclient.Config{}
anonConfig.Host = clientConfig.Host
anonConfig.CAFile = clientConfig.CAFile
anonConfig.CAData = clientConfig.CAData
// Make sure we can't authenticate
if _, err := tokencmd.RequestToken(&anonConfig, nil, "username", "password"); err == nil {
t.Error("Expected error, got none")
}
// Update the htpasswd file with output of `htpasswd -n -b username password`
userpass := "username:$apr1$4Ci5I8yc$85R9vc4fOgzAULsldiUuv."
ioutil.WriteFile(htpasswdFile.Name(), []byte(userpass), os.FileMode(0600))
// Make sure we can get a token
accessToken, err := tokencmd.RequestToken(&anonConfig, nil, "username", "password")
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(accessToken) == 0 {
t.Errorf("Expected access token, got none")
}
// Make sure we can use the token, and it represents who we expect
userConfig := anonConfig
userConfig.BearerToken = accessToken
userClient, err := client.New(&userConfig)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
user, err := userClient.Users().Get("~")
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if user.Name != "username" {
t.Fatalf("Expected username as the user, got %v", user)
}
}
示例13: TestOAuthLDAP
//.........这里部分代码省略.........
CA: "",
Attributes: configapi.LDAPAttributes{
ID: []string{idAttr1, idAttr2},
PreferredUsername: []string{loginAttr1, loginAttr2},
Name: []string{nameAttr1, nameAttr2},
Email: []string{emailAttr1, emailAttr2},
},
},
},
}
clusterAdminKubeConfig, err := testutil.StartConfiguredMaster(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Use the server and CA info
anonConfig := kclient.Config{}
anonConfig.Host = clusterAdminClientConfig.Host
anonConfig.CAFile = clusterAdminClientConfig.CAFile
anonConfig.CAData = clusterAdminClientConfig.CAData
// Make sure we can't authenticate as a missing user
ldapServer.ResetRequests()
if _, err := tokencmd.RequestToken(&anonConfig, nil, myUserUID, myUserPassword); err == nil {
t.Error("Expected error, got none")
}
if len(ldapServer.BindRequests) != 1 {
t.Error("Expected a single bind request for the search phase, got %d:\n%#v", len(ldapServer.BindRequests), ldapServer.BindRequests)
}
if len(ldapServer.SearchRequests) != 1 {
t.Error("Expected a single search request, got %d:\n%#v", len(ldapServer.BindRequests), ldapServer.BindRequests)
}
// Add user
ldapServer.SetPassword(myUserDN, myUserPassword)
ldapServer.AddSearchResult(myUserDN, map[string]string{emailAttr2: myUserEmail, nameAttr2: myUserName, loginAttr2: myUserUID})
// Make sure we can't authenticate with a bad password
ldapServer.ResetRequests()
if _, err := tokencmd.RequestToken(&anonConfig, nil, myUserUID, "badpassword"); err == nil {
t.Error("Expected error, got none")
}
if len(ldapServer.BindRequests) != 2 {
t.Error("Expected a bind request for the search phase and a failed bind request for the auth phase, got %d:\n%#v", len(ldapServer.BindRequests), ldapServer.BindRequests)
}
if len(ldapServer.SearchRequests) != 1 {
t.Error("Expected a single search request, got %d:\n%#v", len(ldapServer.BindRequests), ldapServer.BindRequests)
}
// Make sure we can get a token with a good password
ldapServer.ResetRequests()
accessToken, err := tokencmd.RequestToken(&anonConfig, nil, myUserUID, myUserPassword)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(accessToken) == 0 {
示例14: gatherAuthInfo
// Negotiate a bearer token with the auth server, or try to reuse one based on the
// information already present. In case of any missing information, ask for user input
// (usually username and password, interactive depending on the Reader).
func (o *LoginOptions) gatherAuthInfo() error {
directClientConfig, err := o.getClientConfig()
if err != nil {
return err
}
// make a copy and use it to avoid mutating the original
t := *directClientConfig
clientConfig := &t
// if a token were explicitly provided, try to use it
if o.tokenProvided() {
clientConfig.BearerToken = o.Token
if me, err := whoAmI(clientConfig); err == nil {
o.Username = me.Name
o.Config = clientConfig
fmt.Fprintf(o.Out, "Logged into %q as %q using the token provided.\n\n", o.Config.Host, o.Username)
return nil
} else {
if kerrors.IsUnauthorized(err) {
return fmt.Errorf("The token provided is invalid or expired.\n\n")
}
return err
}
}
// if a username was provided try to make use of it, but if a password were provided we force a token
// request which will return a proper response code for that given password
if o.usernameProvided() && !o.passwordProvided() {
// search all valid contexts with matching server stanzas to see if we have a matching user stanza
kubeconfig := *o.StartingKubeConfig
matchingClusters := getMatchingClusters(*clientConfig, kubeconfig)
for key, context := range o.StartingKubeConfig.Contexts {
if matchingClusters.Has(context.Cluster) {
clientcmdConfig := kclientcmd.NewDefaultClientConfig(kubeconfig, &kclientcmd.ConfigOverrides{CurrentContext: key})
if kubeconfigClientConfig, err := clientcmdConfig.ClientConfig(); err == nil {
if me, err := whoAmI(kubeconfigClientConfig); err == nil && (o.Username == me.Name) {
clientConfig.BearerToken = kubeconfigClientConfig.BearerToken
clientConfig.CertFile = kubeconfigClientConfig.CertFile
clientConfig.CertData = kubeconfigClientConfig.CertData
clientConfig.KeyFile = kubeconfigClientConfig.KeyFile
clientConfig.KeyData = kubeconfigClientConfig.KeyData
o.Config = clientConfig
fmt.Fprintf(o.Out, "Logged into %q as %q using existing credentials.\n\n", o.Config.Host, o.Username)
return nil
}
}
}
}
}
// if kubeconfig doesn't already have a matching user stanza...
clientConfig.BearerToken = ""
clientConfig.CertData = []byte{}
clientConfig.KeyData = []byte{}
clientConfig.CertFile = o.CertFile
clientConfig.KeyFile = o.KeyFile
token, err := tokencmd.RequestToken(o.Config, o.Reader, o.Username, o.Password)
if err != nil {
return err
}
clientConfig.BearerToken = token
me, err := whoAmI(clientConfig)
if err != nil {
return err
}
o.Username = me.Name
o.Config = clientConfig
fmt.Fprint(o.Out, "Login successful.\n\n")
return nil
}
示例15: TestUnprivilegedNewProjectFromTemplate
func TestUnprivilegedNewProjectFromTemplate(t *testing.T) {
namespace := "foo"
templateName := "bar"
masterOptions, err := testserver.DefaultMasterOptions()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
masterOptions.ProjectConfig.ProjectRequestTemplate = namespace + "/" + templateName
clusterAdminKubeConfig, err := testserver.StartConfiguredMaster(masterOptions)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
valerieClientConfig := *clusterAdminClientConfig
valerieClientConfig.Username = ""
valerieClientConfig.Password = ""
valerieClientConfig.BearerToken = ""
valerieClientConfig.CertFile = ""
valerieClientConfig.KeyFile = ""
valerieClientConfig.CertData = nil
valerieClientConfig.KeyData = nil
accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
valerieClientConfig.BearerToken = accessToken
valerieOpenshiftClient, err := client.New(&valerieClientConfig)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if _, err := clusterAdminClient.Projects().Create(&projectapi.Project{ObjectMeta: kapi.ObjectMeta{Name: namespace}}); err != nil {
t.Fatalf("unexpected error: %v", err)
}
template := projectrequeststorage.DefaultTemplate()
template.Name = templateName
template.Namespace = namespace
template.Objects[0].(*projectapi.Project).Annotations["extra"] = "here"
_, err = clusterAdminClient.Templates(namespace).Create(template)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
requestProject := oc.NewProjectOptions{
ProjectName: "new-project",
DisplayName: "display name here",
Description: "the special description",
Client: valerieOpenshiftClient,
Out: ioutil.Discard,
}
if err := requestProject.Run(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
waitForProject(t, valerieOpenshiftClient, "new-project", 5*time.Second, 10)
project, err := valerieOpenshiftClient.Projects().Get("new-project")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if project.Annotations["extra"] != "here" {
t.Errorf("unexpected project %#v", project)
}
if err := clusterAdminClient.Templates(namespace).Delete(templateName); err != nil {
t.Fatalf("unexpected error: %v", err)
}
requestProject.ProjectName = "different"
// This should fail during the template retrieve
if err := requestProject.Run(); !kapierrors.IsNotFound(err) {
t.Fatalf("expected a not found error, but got %v", err)
}
}