diff --git a/mongodb/kubedb_client_builder.go b/mongodb/kubedb_client_builder.go index 81eafdcf4..46b37001a 100644 --- a/mongodb/kubedb_client_builder.go +++ b/mongodb/kubedb_client_builder.go @@ -42,6 +42,8 @@ type KubeDBClientBuilder struct { direct bool certs *certholder.ResourceCerts ctx context.Context + cred string + authDB string } func NewKubeDBClientBuilder(kc client.Client, db *api.MongoDB) *KubeDBClientBuilder { @@ -52,6 +54,18 @@ func NewKubeDBClientBuilder(kc client.Client, db *api.MongoDB) *KubeDBClientBuil } } +// To connect with a specific user. +// cred formet: "username:password" +func (o *KubeDBClientBuilder) WithCred(cred string) *KubeDBClientBuilder { + o.cred = cred + return o +} + +func (o *KubeDBClientBuilder) WithAuthDatabase(authDB string) *KubeDBClientBuilder { + o.authDB = authDB + return o +} + func (o *KubeDBClientBuilder) WithURL(url string) *KubeDBClientBuilder { o.url = url return o @@ -144,18 +158,33 @@ func (o *KubeDBClientBuilder) getMongoDBClientOpts() (*mgoptions.ClientOptions, if o.repSetName != "" { repSetConfig = "replicaSet=" + o.repSetName + "&" } + authDatabase := "" + if o.authDB != "" { + authDatabase = "authSource=" + o.authDB + } - user, pass, err := o.getMongoDBRootCredentials() - if err != nil { - return nil, err + cred := o.cred + if cred == "" { + user, pass, err := o.getMongoDBRootCredentials() + if err != nil { + return nil, err + } + cred = fmt.Sprintf("%s:%s", user, pass) } + var clientOpts *mgoptions.ClientOptions if db.Spec.TLS != nil { + if o.authDB != "" { + authDatabase = "&" + authDatabase + } secretName := db.GetCertSecretName(api.MongoDBClientCert, "") - var paths *certholder.Paths + var ( + paths *certholder.Paths + err error + ) if o.certs == nil { var certSecret core.Secret - err := o.kc.Get(o.ctx, client.ObjectKey{Namespace: db.Namespace, Name: secretName}, &certSecret) + err = o.kc.Get(o.ctx, client.ObjectKey{Namespace: db.Namespace, Name: secretName}, &certSecret) if err != nil { klog.Error(err, "failed to get certificate secret. ", secretName) return nil, err @@ -180,10 +209,10 @@ func (o *KubeDBClientBuilder) getMongoDBClientOpts() (*mgoptions.ClientOptions, } } - uri := fmt.Sprintf("mongodb://%s:%s@%s/admin?%vtls=true&tlsCAFile=%v&tlsCertificateKeyFile=%v", user, pass, o.url, repSetConfig, paths.CACert, paths.Pem) + uri := fmt.Sprintf("mongodb://%s@%s/admin?%vtls=true&tlsCAFile=%v&tlsCertificateKeyFile=%v%v", cred, o.url, repSetConfig, paths.CACert, paths.Pem, authDatabase) clientOpts = mgoptions.Client().ApplyURI(uri) } else { - clientOpts = mgoptions.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%s@%s/admin?%v", user, pass, o.url, repSetConfig)) + clientOpts = mgoptions.Client().ApplyURI(fmt.Sprintf("mongodb://%s@%s/admin?%v%v", cred, o.url, repSetConfig, authDatabase)) } clientOpts.SetDirect(o.direct)