From 0eb8447110ef47f9659eeb765b1055462102b089 Mon Sep 17 00:00:00 2001 From: Luca Berneking Date: Thu, 6 Jun 2024 11:31:44 +0200 Subject: [PATCH] Implement Userpass auth --- client_opts.go | 13 +++++++++++ userpass_auth.go | 57 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 userpass_auth.go diff --git a/client_opts.go b/client_opts.go index aea0d9e..c519c35 100644 --- a/client_opts.go +++ b/client_opts.go @@ -21,3 +21,16 @@ func WithAuthToken(token string) ClientOpts { return nil } } + +func WithUserpassAuth(username string, password string, opts ...UserpassAuthOpt) ClientOpts { + return func(c *Client) error { + userpassAuthProvider, err := NewUserpassAuth(c, username, password, opts...) + if err != nil { + return err + } + + c.auth = userpassAuthProvider + + return nil + } +} diff --git a/userpass_auth.go b/userpass_auth.go new file mode 100644 index 0000000..c8ae740 --- /dev/null +++ b/userpass_auth.go @@ -0,0 +1,57 @@ +package vault + +func NewUserpassAuth(c *Client, username string, password string, opts ...UserpassAuthOpt) (AuthProvider, error) { + k := &UserpassAuth{ + Client: c, + mountPoint: "userpass", + username: username, + password: password, + } + + for _, opt := range opts { + err := opt(k) + if err != nil { + return nil, err + } + } + + return k, nil +} + +type UserpassAuth struct { + Client *Client + mountPoint string + username string + password string +} + +type userpassAuthConfig struct { + Password string `json:"password"` +} + +func (k UserpassAuth) Auth() (*AuthResponse, error) { + conf := &userpassAuthConfig{ + Password: k.password, + } + + res := &AuthResponse{} + + err := k.Client.Write([]string{"v1", "auth", k.mountPoint, "login", k.username}, conf, res, &RequestOptions{ + SkipRenewal: true, + }) + if err != nil { + return nil, err + } + + return res, nil +} + +type UserpassAuthOpt func(k *UserpassAuth) error + +func WithUserpassMountPoint(mountPoint string) UserpassAuthOpt { + return func(k *UserpassAuth) error { + k.mountPoint = mountPoint + + return nil + } +}