From 2def328f6a14cd9a73a2e8ad0df6186593e67f07 Mon Sep 17 00:00:00 2001 From: Darko Djalevski Date: Sat, 27 Mar 2021 15:55:59 +0100 Subject: [PATCH] fix: fix email validating in shell input fix: test cases fix feedback fix: validate email with custom validator in shell input --- pkg/bastion/shell.go | 7 +++++-- pkg/utils/emailvalidator.go | 13 +++++++++++++ pkg/utils/emailvalidator_test.go | 22 ++++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 pkg/utils/emailvalidator.go create mode 100644 pkg/utils/emailvalidator_test.go diff --git a/pkg/bastion/shell.go b/pkg/bastion/shell.go index 266f936..f7c9a31 100644 --- a/pkg/bastion/shell.go +++ b/pkg/bastion/shell.go @@ -25,6 +25,7 @@ import ( "golang.org/x/crypto/ssh/terminal" "moul.io/sshportal/pkg/crypto" "moul.io/sshportal/pkg/dbmodels" + "moul.io/sshportal/pkg/utils" ) var banner = ` @@ -1623,9 +1624,11 @@ GLOBAL OPTIONS: return err } - // FIXME: validate email - email := c.Args().First() + valid := utils.ValidateEmail(email) + if !valid { + return errors.New("invalid email") + } name := strings.Split(email, "@")[0] if c.String("name") != "" { name = c.String("name") diff --git a/pkg/utils/emailvalidator.go b/pkg/utils/emailvalidator.go new file mode 100644 index 0000000..6a5923d --- /dev/null +++ b/pkg/utils/emailvalidator.go @@ -0,0 +1,13 @@ +package utils + +import "regexp" + +var emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") + +// ValidateEmail validates email. +func ValidateEmail(e string) bool { + if len(e) < 3 && len(e) > 254 { + return false + } + return emailRegex.MatchString(e) +} diff --git a/pkg/utils/emailvalidator_test.go b/pkg/utils/emailvalidator_test.go new file mode 100644 index 0000000..2b5e652 --- /dev/null +++ b/pkg/utils/emailvalidator_test.go @@ -0,0 +1,22 @@ +package utils + +import ( + "testing" +) + +func TestValidateEmail(t *testing.T) { + + goodEmail := "goodemail@email.com" + badEmail := "b@2323.22" + + got := ValidateEmail(goodEmail) + if got == false { + t.Errorf("got1= %v; want true", got) + } + + got2 := ValidateEmail(badEmail) + if got2 == false { + t.Errorf("got2= %v; want false", got2) + } + +}