From 746a508df14c565d2074e2919d27c2efd1a7fe89 Mon Sep 17 00:00:00 2001 From: Kyle Spiers Date: Thu, 23 Nov 2017 03:56:11 -0800 Subject: [PATCH] Add validation on username Signed-off-by: Kyle Spiers --- core/core.go | 8 ++++++-- core/core_test.go | 10 ++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/core/core.go b/core/core.go index 1d6c645..d05e536 100644 --- a/core/core.go +++ b/core/core.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "log" + "regexp" "strconv" "strings" "time" @@ -219,10 +220,13 @@ func validateUser(name, password string, admin bool) error { return nil } +//Username must start with an alphanumeric character and can include "-" and "_" after the first +var validName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9\_\-]*$`).MatchString + // validateName checks that the username and password pass a validation test. func validateName(name, password string) error { - if name == "" { - return errors.New("User name must not be blank") + if !validName(name) { + return errors.New("must start with an alphanumeric character and can include \"-\" or \"_\" after the first character") } if password == "" { return errors.New("Password must be at least one character") diff --git a/core/core_test.go b/core/core_test.go index 8fa8e33..8de0259 100644 --- a/core/core_test.go +++ b/core/core_test.go @@ -1174,6 +1174,16 @@ func TestValidateName(t *testing.T) { t.Fatal("Error expected when no name is provided") } + err = validateName("?", "password") + if err == nil { + t.Fatal("Error expected when non alphanumeric is used in name") + } + + err = validateName("-name", "password") + if err == nil { + t.Fatal("Error expected when name starts with '-' or '_'") + } + err = validateName("username", "") if err == nil { t.Fatal("Error expected when no password is provided")