Add "GET /register/available?username=...." endpoint

Signed-off-by: MTRNord <mtrnord1@gmail.com>
This commit is contained in:
MTRNord 2017-10-07 00:46:49 +02:00
parent 619fec6113
commit fbd54f6efb
No known key found for this signature in database
GPG key ID: E5B89311FAB91B9F
2 changed files with 69 additions and 0 deletions

View file

@ -0,0 +1,65 @@
package readers
import (
"fmt"
"github.com/matrix-org/dendrite/clientapi/auth/storage/accounts"
"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/util"
"net/http"
"regexp"
)
const (
maxUsernameLength = 254 // http://matrix.org/speculator/spec/HEAD/intro.html#user-identifiers TODO account for domain
)
var validUsernameRegex = regexp.MustCompile(`^[0-9a-zA-Z_\-./]+$`)
func validate(username string) *util.JSONResponse {
if len(username) > maxUsernameLength {
return &util.JSONResponse{
Code: 400,
JSON: jsonerror.BadJSON(fmt.Sprintf("'username' >%d characters", maxUsernameLength)),
}
} 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
}
type availableResponse struct {
Available bool `json:"available"`
}
func RegisterAvailable(
req *http.Request,
accountDB *accounts.Database,
) util.JSONResponse {
username := req.URL.Query().Get("username")
if resErr := validate(username); resErr != nil {
return *resErr
}
if _, resErr := accountDB.GetProfileByLocalpart(req.Context(), username); resErr == nil {
return util.JSONResponse{
Code: 400,
JSON: jsonerror.InvalidUsername("A different user ID has already been registered for this session"),
}
}
return util.JSONResponse{
Code: 200,
JSON: availableResponse{
Available: true,
},
}
}

View file

@ -131,6 +131,10 @@ func Setup(
return writers.LegacyRegister(req, accountDB, deviceDB, &cfg) return writers.LegacyRegister(req, accountDB, deviceDB, &cfg)
})).Methods("POST", "OPTIONS") })).Methods("POST", "OPTIONS")
r0mux.Handle("/register/available", common.MakeExternalAPI("registerAvailable", func(req *http.Request) util.JSONResponse {
return readers.RegisterAvailable(req, accountDB)
})).Methods("GET", "OPTIONS")
r0mux.Handle("/directory/room/{roomAlias}", r0mux.Handle("/directory/room/{roomAlias}",
common.MakeAuthAPI("directory_room", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse { common.MakeAuthAPI("directory_room", deviceDB, func(req *http.Request, device *authtypes.Device) util.JSONResponse {
vars := mux.Vars(req) vars := mux.Vars(req)