From 8a213457064308015404cb2e70b5f66b6c780f53 Mon Sep 17 00:00:00 2001 From: Stavros Date: Thu, 10 Apr 2025 15:34:46 +0300 Subject: [PATCH] fix: handle new lines and spaces in the secret files --- internal/utils/utils.go | 38 ++++++++++++++++++++++++++---------- internal/utils/utils_test.go | 3 ++- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/internal/utils/utils.go b/internal/utils/utils.go index 783642c..b60f8c6 100644 --- a/internal/utils/utils.go +++ b/internal/utils/utils.go @@ -130,7 +130,7 @@ func GetSecret(conf string, file string) string { } // Return the contents of the file - return contents + return ParseSecretFile(contents) } // Get the users from the config or file @@ -241,23 +241,21 @@ func ParseUser(user string) (types.User, error) { return types.User{}, errors.New("invalid user format") } - // Check if the user has a totp secret - if len(userSplit) == 2 { - // Check for empty username or password - if userSplit[1] == "" || userSplit[0] == "" { + // Check for empty strings + for _, userPart := range userSplit { + if strings.TrimSpace(userPart) == "" { return types.User{}, errors.New("invalid user format") } + } + + // Check if the user has a totp secret + if len(userSplit) == 2 { return types.User{ Username: userSplit[0], Password: userSplit[1], }, nil } - // Check for empty username, password or totp secret - if userSplit[2] == "" || userSplit[1] == "" || userSplit[0] == "" { - return types.User{}, errors.New("invalid user format") - } - // Return the user struct return types.User{ Username: userSplit[0], @@ -265,3 +263,23 @@ func ParseUser(user string) (types.User, error) { TotpSecret: userSplit[2], }, nil } + +// Parse secret file +func ParseSecretFile(contents string) string { + // Split to lines + lines := strings.Split(contents, "\n") + + // Loop through the lines + for _, line := range lines { + // Check if the line is empty + if strings.TrimSpace(line) == "" { + continue + } + + // Return the line + return strings.TrimSpace(line) + } + + // Return an empty string + return "" +} diff --git a/internal/utils/utils_test.go b/internal/utils/utils_test.go index 2750310..e859f8d 100644 --- a/internal/utils/utils_test.go +++ b/internal/utils/utils_test.go @@ -1,6 +1,7 @@ package utils_test import ( + "fmt" "os" "reflect" "testing" @@ -123,7 +124,7 @@ func TestGetSecret(t *testing.T) { expected := "test" // Create file - err := os.WriteFile(file, []byte(expected), 0644) + err := os.WriteFile(file, []byte(fmt.Sprintf("\n\n \n\n\n %s \n\n \n ", expected)), 0644) // Check if there was an error if err != nil {