mirror of
https://github.com/woodpecker-ci/woodpecker.git
synced 2024-11-24 08:02:18 +02:00
username validation fixes #1418
This commit is contained in:
parent
0f693cb66d
commit
631cd10033
@ -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
|
||||
}
|
||||
}
|
||||
|
46
model/user_test.go
Normal file
46
model/user_test.go
Normal file
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user