From 4d2cf611757353ca9d058db5bed9a5faea81627d Mon Sep 17 00:00:00 2001 From: Shashank Prasad Date: Tue, 24 Sep 2024 14:10:23 -0700 Subject: [PATCH] Generate complex password --- internal/controller/mysqluser_controller.go | 6 ++++- internal/utils/utils_oci.go | 28 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 internal/utils/utils_oci.go diff --git a/internal/controller/mysqluser_controller.go b/internal/controller/mysqluser_controller.go index 1b98ef1..f6478c2 100644 --- a/internal/controller/mysqluser_controller.go +++ b/internal/controller/mysqluser_controller.go @@ -190,7 +190,11 @@ func (r *MySQLUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) ( if err != nil { if errors.IsNotFound(err) { // Secret doesn't exists -> generate password log.Info("[password] Generate new password for Secret", "secretName", secretName) - password = utils.GenerateRandomString(16) + password, genErr := utils.GenerateComplexRandomString(16) + if genErr != nil { + log.Error(genErr, "[password] Failed to generate password") + return ctrl.Result{}, genErr // Handle error + } } else { log.Error(err, "[password] Failed to get Secret", "secretName", secretName) return ctrl.Result{}, err // requeue diff --git a/internal/utils/utils_oci.go b/internal/utils/utils_oci.go new file mode 100644 index 0000000..cb5ca16 --- /dev/null +++ b/internal/utils/utils_oci.go @@ -0,0 +1,28 @@ +package utils + +import ( + "crypto/rand" + "math/big" +) + +const ( + letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + numberBytes = "0123456789" + specialBytes = "!@#$%^&*()-_=+[]{}|;:,.<>?/~`" + allBytes = letterBytes + numberBytes + specialBytes +) + +// GenerateComplexRandomString generates a random string of specified length with a mix of letters, numbers, and special characters. +func GenerateComplexRandomString(length int) (string, error) { + result := make([]byte, length) + + for i := 0; i < length; i++ { + index, err := rand.Int(rand.Reader, big.NewInt(int64(len(allBytes)))) + if err != nil { + return "", err + } + result[i] = allBytes[index.Int64()] + } + return string(result), nil +} +