-
Notifications
You must be signed in to change notification settings - Fork 0
/
reset_credentials.go
263 lines (212 loc) · 8.74 KB
/
reset_credentials.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package resetcredentials
import (
"context"
"errors"
"fmt"
"os"
kafkamgmtclient "github.com/redhat-developer/app-services-sdk-go/kafkamgmt/apiv1/client"
"github.com/aerogear/charmil-host-example/pkg/connection"
"github.com/aerogear/charmil/core/utils/localize"
"github.com/AlecAivazis/survey/v2"
flagutil "github.com/aerogear/charmil-host-example/pkg/cmdutil/flags"
"github.com/aerogear/charmil-host-example/pkg/serviceaccount/credentials"
"github.com/aerogear/charmil-host-example/pkg/serviceaccount/validation"
"github.com/aerogear/charmil/core/utils/iostreams"
"github.com/aerogear/charmil-host-example/pkg/cmd/factory"
"github.com/aerogear/charmil-host-example/pkg/cmd/flag"
"github.com/aerogear/charmil-host-example/pkg/config"
"github.com/spf13/cobra"
"github.com/aerogear/charmil/core/utils/logging"
)
type Options struct {
IO *iostreams.IOStreams
CfgHandler *config.CfgHandler
Connection factory.ConnectionFunc
Logger func() (logging.Logger, error)
localizer localize.Localizer
id string
fileFormat string
overwrite bool
filename string
interactive bool
force bool
}
// NewResetCredentialsCommand creates a new command to delete a service account
func NewResetCredentialsCommand(f *factory.Factory) *cobra.Command {
opts := &Options{
IO: f.IOStreams,
CfgHandler: f.CfgHandler,
Connection: f.Connection,
Logger: f.Logger,
localizer: f.Localizer,
}
cmd := &cobra.Command{
Use: opts.localizer.LocalizeByID("serviceAccount.resetCredentials.cmd.use"),
Short: opts.localizer.LocalizeByID("serviceAccount.resetCredentials.cmd.shortDescription"),
Long: opts.localizer.LocalizeByID("serviceAccount.resetCredentials.cmd.longDescription"),
Example: opts.localizer.LocalizeByID("serviceAccount.resetCredentials.cmd.example"),
RunE: func(cmd *cobra.Command, _ []string) error {
if !opts.IO.CanPrompt() && opts.id == "" {
return errors.New(opts.localizer.LocalizeByID("flag.error.requiredWhenNonInteractive", localize.NewEntry("Flag", "id")))
} else if opts.id == "" {
opts.interactive = true
}
if !opts.interactive && opts.fileFormat == "" {
return errors.New(opts.localizer.LocalizeByID("flag.error.requiredWhenNonInteractive", localize.NewEntry("Flag", "file-format")))
}
validOutput := flagutil.IsValidInput(opts.fileFormat, flagutil.CredentialsOutputFormats...)
if !validOutput && opts.fileFormat != "" {
return flag.InvalidValueError("file-format", opts.fileFormat, flagutil.CredentialsOutputFormats...)
}
if !opts.interactive {
validator := &validation.Validator{
Localizer: opts.localizer,
}
validID := validator.ValidateUUID(opts.id)
if validID != nil {
return validID
}
}
return runResetCredentials(opts)
},
}
cmd.Flags().StringVar(&opts.id, "id", "", opts.localizer.LocalizeByID("serviceAccount.resetCredentials.flag.id.description"))
cmd.Flags().BoolVar(&opts.overwrite, "overwrite", false, opts.localizer.LocalizeByID("serviceAccount.common.flag.overwrite.description"))
cmd.Flags().StringVar(&opts.filename, "file-location", "", opts.localizer.LocalizeByID("serviceAccount.common.flag.fileLocation.description"))
cmd.Flags().StringVar(&opts.fileFormat, "file-format", "", opts.localizer.LocalizeByID("serviceAccount.common.flag.fileFormat.description"))
cmd.Flags().BoolVarP(&opts.force, "yes", "y", false, opts.localizer.LocalizeByID("serviceAccount.resetCredentials.flag.yes.description"))
flagutil.EnableStaticFlagCompletion(cmd, "file-format", flagutil.CredentialsOutputFormats)
return cmd
}
// nolint:funlen
func runResetCredentials(opts *Options) (err error) {
connection, err := opts.Connection(connection.DefaultConfigSkipMasAuth)
if err != nil {
return err
}
logger, err := opts.Logger()
if err != nil {
return err
}
api := connection.API()
serviceacct, _, err := api.ServiceAccount().GetServiceAccountById(context.Background(), opts.id).Execute()
if err != nil {
return err
}
serviceAcctName := serviceacct.GetName()
if opts.interactive {
err = runInteractivePrompt(opts)
if err != nil {
return err
}
} else if opts.filename == "" {
// obtain the default absolute path to where credentials will be saved
opts.filename = credentials.GetDefaultPath(opts.fileFormat)
}
// If the credentials file already exists, and the --overwrite flag is not set then return an error
// indicating that the user should explicitly request overwriting of the file
if _, err = os.Stat(opts.filename); err == nil && !opts.overwrite {
return errors.New(opts.localizer.LocalizeByID("serviceAccount.common.error.credentialsFileAlreadyExists", localize.NewEntry("FilePath", opts.filename)))
}
if !opts.force {
// prompt the user to confirm their wish to proceed with this action
var confirmReset bool
opts.localizer.LocalizeByID("serviceAccount.resetCredentials.input.confirmReset.message", localize.NewEntry("ID", opts.id))
promptConfirmDelete := &survey.Confirm{
Message: opts.localizer.LocalizeByID("serviceAccount.resetCredentials.input.confirmReset.message", localize.NewEntry("ID", opts.id)),
}
if err = survey.AskOne(promptConfirmDelete, &confirmReset); err != nil {
return err
}
if !confirmReset {
logger.Infoln(opts.localizer.LocalizeByID("serviceAccount.resetCredentials.log.debug.cancelledReset"))
return nil
}
}
updatedServiceAccount, err := resetCredentials(serviceAcctName, opts)
if err != nil {
return fmt.Errorf("%v: %w", opts.localizer.LocalizeByID("serviceAccount.resetCredentials.error.resetError", localize.NewEntry("Name", updatedServiceAccount.GetName())), err)
}
logger.Info(opts.localizer.LocalizeByID("serviceAccount.resetCredentials.log.info.resetSuccess", localize.NewEntry("Name", updatedServiceAccount.GetName())))
creds := &credentials.Credentials{
ClientID: updatedServiceAccount.GetClientId(),
ClientSecret: updatedServiceAccount.GetClientSecret(),
}
// save the credentials to a file
err = credentials.Write(opts.fileFormat, opts.filename, creds)
if err != nil {
return err
}
logger.Info(opts.localizer.LocalizeByID("serviceAccount.common.log.info.credentialsSaved", localize.NewEntry("FilePath", opts.filename)))
return nil
}
func resetCredentials(name string, opts *Options) (*kafkamgmtclient.ServiceAccount, error) {
connection, err := opts.Connection(connection.DefaultConfigSkipMasAuth)
if err != nil {
return nil, err
}
// check if the service account exists
api := connection.API()
logger, err := opts.Logger()
if err != nil {
return nil, err
}
logger.Infoln(opts.localizer.LocalizeByID("serviceAccount.resetCredentials.log.debug.resettingCredentials", localize.NewEntry("Name", name)))
serviceacct, httpRes, err := api.ServiceAccount().ResetServiceAccountCreds(context.Background(), opts.id).Execute()
if err != nil {
if httpRes == nil {
return nil, err
}
switch httpRes.StatusCode {
case 403:
opts.localizer.LocalizeByID("serviceAccount.common.error.forbidden", localize.NewEntry("Operation", "update"))
return nil, fmt.Errorf("%v: %w", opts.localizer.LocalizeByID("serviceAccount.common.error.forbidden", localize.NewEntry("Operation", "update")), err)
case 500:
return nil, errors.New(opts.localizer.LocalizeByID("serviceAccount.common.error.internalServerError"))
default:
return nil, err
}
}
return &serviceacct, nil
}
func runInteractivePrompt(opts *Options) (err error) {
_, err = opts.Connection(connection.DefaultConfigSkipMasAuth)
if err != nil {
return err
}
logger, err := opts.Logger()
if err != nil {
return err
}
logger.Infoln(opts.localizer.LocalizeByID("common.log.debug.startingInteractivePrompt"))
promptID := &survey.Input{
Message: opts.localizer.LocalizeByID("serviceAccount.resetCredentials.input.id.message"),
Help: opts.localizer.LocalizeByID("serviceAccount.resetCredentials.input.id.help"),
}
validator := &validation.Validator{
Localizer: opts.localizer,
}
err = survey.AskOne(promptID, &opts.id, survey.WithValidator(survey.Required), survey.WithValidator(validator.ValidateUUID))
if err != nil {
return err
}
// if the --output flag was not used, ask in the prompt
if opts.fileFormat == "" {
logger.Infoln(opts.localizer.LocalizeByID("serviceAccount.common.log.debug.interactive.fileFormatNotSet"))
fileFormatPrompt := &survey.Select{
Message: opts.localizer.LocalizeByID("serviceAccount.resetCredentials.input.fileFormat.message"),
Help: opts.localizer.LocalizeByID("serviceAccount.resetCredentials.input.fileFormat.help"),
Options: flagutil.CredentialsOutputFormats,
Default: "env",
}
err = survey.AskOne(fileFormatPrompt, &opts.fileFormat)
if err != nil {
return err
}
}
opts.filename, opts.overwrite, err = credentials.ChooseFileLocation(opts.fileFormat, opts.filename, opts.overwrite)
if err != nil {
return err
}
return err
}