fix init with empty options #115

Merged
vtolstov merged 1 commits from initfix into v3 2023-06-03 23:20:06 +03:00
Showing only changes of commit 0015bbd209 - Show all commits

View File

@ -16,9 +16,12 @@ import (
var DefaultStructTag = "vault" var DefaultStructTag = "vault"
type vaultConfig struct { type vaultConfig struct {
path string path string
cli *api.Client token string
opts config.Options roleID string
secretID string
cli *api.Client
opts config.Options
} }
func (c *vaultConfig) Options() config.Options { func (c *vaultConfig) Options() config.Options {
@ -95,39 +98,12 @@ func (c *vaultConfig) Init(opts ...config.Option) error {
} }
c.cli = cli c.cli = cli
c.path = path c.path = path
c.token = token
c.roleID = roleID
c.secretID = secretID
if token != "" { if err = c.setToken(); err != nil && !c.opts.AllowFail {
cli.SetToken(token) return err
if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail {
return err
}
return nil
} else if roleID == "" || secretID == "" {
if !c.opts.AllowFail {
return fmt.Errorf("missing Token or RoleID and SecretID")
}
if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail {
return err
}
return nil
}
rsp, err := cli.Logical().Write("auth/approle/login", map[string]interface{}{
"role_id": roleID,
"secret_id": secretID,
})
if err != nil {
if !c.opts.AllowFail {
return err
}
} else if err == nil {
cli.SetToken(rsp.Auth.ClientToken)
} }
if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail { if err := config.DefaultAfterInit(c.opts.Context, c); err != nil && !c.opts.AllowFail {
@ -137,6 +113,28 @@ func (c *vaultConfig) Init(opts ...config.Option) error {
return nil return nil
} }
func (c *vaultConfig) setToken() error {
if c.token != "" {
c.cli.SetToken(c.token)
}
if c.roleID != "" && c.secretID != "" {
rsp, err := c.cli.Logical().Write("auth/approle/login", map[string]interface{}{
"role_id": c.roleID,
"secret_id": c.secretID,
})
if err != nil {
if !c.opts.AllowFail {
return err
}
} else if err == nil {
c.cli.SetToken(rsp.Auth.ClientToken)
}
}
return nil
}
func (c *vaultConfig) Load(ctx context.Context, opts ...config.LoadOption) error { func (c *vaultConfig) Load(ctx context.Context, opts ...config.LoadOption) error {
if err := config.DefaultBeforeLoad(ctx, c); err != nil { if err := config.DefaultBeforeLoad(ctx, c); err != nil {
return err return err