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