Correctly check username validility

This commit is contained in:
Erik Johnston 2017-09-22 15:25:15 +01:00
parent b2f72e4f44
commit 890b481692
2 changed files with 24 additions and 5 deletions

View file

@ -85,6 +85,12 @@ func WeakPassword(msg string) *MatrixError {
return &MatrixError{"M_WEAK_PASSWORD", msg} return &MatrixError{"M_WEAK_PASSWORD", msg}
} }
// InvalidUsername is an error returned when the client tries to register an
// invalid username
func InvalidUsername(msg string) *MatrixError {
return &MatrixError{"M_INVALID_USERNAME", msg}
}
// GuestAccessForbidden is an error which is returned when the client is // GuestAccessForbidden is an error which is returned when the client is
// forbidden from accessing a resource as a guest. // forbidden from accessing a resource as a guest.
func GuestAccessForbidden(msg string) *MatrixError { func GuestAccessForbidden(msg string) *MatrixError {

View file

@ -7,6 +7,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
"regexp"
"strings" "strings"
"time" "time"
@ -29,6 +30,8 @@ const (
maxUsernameLength = 254 // http://matrix.org/speculator/spec/HEAD/intro.html#user-identifiers TODO account for domain maxUsernameLength = 254 // http://matrix.org/speculator/spec/HEAD/intro.html#user-identifiers TODO account for domain
) )
var validUsernameRegex = regexp.MustCompile(`^[0-9a-zA-Z_\-./]+$`)
// registerRequest represents the submitted registration request. // registerRequest represents the submitted registration request.
// It can be broken down into 2 sections: the auth dictionary and registration parameters. // It can be broken down into 2 sections: the auth dictionary and registration parameters.
// Registration parameters vary depending on the request, and will need to remembered across // Registration parameters vary depending on the request, and will need to remembered across
@ -106,6 +109,16 @@ func validate(username, password string) *util.JSONResponse {
Code: 400, Code: 400,
JSON: jsonerror.WeakPassword(fmt.Sprintf("password too weak: min %d chars", minPasswordLength)), JSON: jsonerror.WeakPassword(fmt.Sprintf("password too weak: min %d chars", minPasswordLength)),
} }
} else if !validUsernameRegex.MatchString(username) {
return &util.JSONResponse{
Code: 400,
JSON: jsonerror.InvalidUsername("User ID can only contain characters a-z, 0-9, or '_-./'"),
}
} else if username[0] == '_' { // Regex checks its not a zero length string
return &util.JSONResponse{
Code: 400,
JSON: jsonerror.InvalidUsername("User ID can't start with a '_'"),
}
} }
return nil return nil
} }