From 631cd100336845577aac2fe8596dfb84c334ff63 Mon Sep 17 00:00:00 2001 From: Brad Rydzewski Date: Mon, 17 Jul 2017 00:01:35 -0400 Subject: [PATCH] username validation fixes #1418 --- model/user.go | 24 ++++++++++++++++++++++++ model/user_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ server/users.go | 4 ++++ 3 files changed, 74 insertions(+) create mode 100644 model/user_test.go diff --git a/model/user.go b/model/user.go index 4f844a1c..ca12bbae 100644 --- a/model/user.go +++ b/model/user.go @@ -1,5 +1,15 @@ package model +import ( + "errors" + "regexp" +) + +// validate a username (e.g. from github) +var reUsername = regexp.MustCompile("^[a-zA-Z0-9-_]+$") + +var errUserLoginInvalid = errors.New("Invalid User Login") + // User represents a registered user. // // swagger:model user @@ -49,3 +59,17 @@ type User struct { // DEPRECATED Admin indicates the user is a system administrator. XAdmin bool `json:"-" meddler:"user_admin"` } + +// Validate validates the required fields and formats. +func (u *User) Validate() error { + switch { + case len(u.Login) == 0: + return errUserLoginInvalid + case len(u.Login) > 250: + return errUserLoginInvalid + case !reUsername.MatchString(u.Login): + return errUserLoginInvalid + default: + return nil + } +} diff --git a/model/user_test.go b/model/user_test.go new file mode 100644 index 00000000..a11eaa1e --- /dev/null +++ b/model/user_test.go @@ -0,0 +1,46 @@ +package model + +import "testing" + +func TestUserValidate(t *testing.T) { + var tests = []struct { + user User + err error + }{ + { + user: User{}, + err: errUserLoginInvalid, + }, + { + user: User{Login: "octocat!"}, + err: errUserLoginInvalid, + }, + { + user: User{Login: "!octocat"}, + err: errUserLoginInvalid, + }, + { + user: User{Login: "john$smith"}, + err: errUserLoginInvalid, + }, + { + user: User{Login: "octocat"}, + err: nil, + }, + { + user: User{Login: "john-smith"}, + err: nil, + }, + { + user: User{Login: "john_smith"}, + err: nil, + }, + } + + for _, test := range tests { + err := test.user.Validate() + if want, got := test.err, err; want != got { + t.Errorf("Want user validation error %s, got %s", want, got) + } + } +} diff --git a/server/users.go b/server/users.go index dbe00357..410e8b8d 100644 --- a/server/users.go +++ b/server/users.go @@ -69,6 +69,10 @@ func PostUser(c *gin.Context) { securecookie.GenerateRandomKey(32), ), } + if err = user.Validate(); err != nil { + c.String(http.StatusBadRequest, err.Error()) + return + } if err = store.CreateUser(c, user); err != nil { c.String(http.StatusInternalServerError, err.Error()) return