diff --git a/pkg/controller/api/username_check.go b/pkg/controller/api/username_check.go new file mode 100644 index 0000000..66886d4 --- /dev/null +++ b/pkg/controller/api/username_check.go @@ -0,0 +1,57 @@ +package api + +import ( + "fmt" + "net/http" + "strings" + + "code.nonshy.com/nonshy/website/pkg/models" +) + +// UsernameCheck API. +func UsernameCheck() http.HandlerFunc { + // Request JSON schema. + type Request struct { + Username string `json:"username"` + } + + // Response JSON schema. + type Response struct { + OK bool `json:"OK"` + Error string `json:"error,omitempty"` + } + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + SendJSON(w, http.StatusNotAcceptable, Response{ + Error: "POST method only", + }) + return + } + + // Parse request payload. + var req Request + if err := ParseJSON(r, &req); err != nil { + SendJSON(w, http.StatusBadRequest, Response{ + Error: fmt.Sprintf("Error with request payload: %s", err), + }) + return + } + + // Username to test. + var username = strings.TrimSpace(strings.ToLower(req.Username)) + + // Does it exist? + if _, err := models.FindUser(username); err == nil { + SendJSON(w, http.StatusOK, Response{ + Error: "That username is already taken, please try another one.", + }) + return + } + + // Send success response. + SendJSON(w, http.StatusOK, Response{ + OK: true, + }) + }) +} diff --git a/pkg/router/router.go b/pkg/router/router.go index 11be908..6ee2ab4 100644 --- a/pkg/router/router.go +++ b/pkg/router/router.go @@ -93,6 +93,7 @@ func New() http.Handler { // JSON API endpoints. mux.HandleFunc("/v1/version", api.Version()) mux.HandleFunc("/v1/users/me", api.LoginOK()) + mux.HandleFunc("/v1/users/check-username", api.UsernameCheck()) mux.Handle("/v1/likes", middleware.LoginRequired(api.Likes())) mux.Handle("/v1/notifications/read", middleware.LoginRequired(api.ReadNotification())) mux.Handle("/v1/notifications/delete", middleware.LoginRequired(api.ClearNotification())) diff --git a/web/templates/account/signup.html b/web/templates/account/signup.html index 79091a9..87ab0a4 100644 --- a/web/templates/account/signup.html +++ b/web/templates/account/signup.html @@ -108,6 +108,20 @@ value="{{.Username}}" required> Usernames are 3 to 32 characters a-z 0-9 . - + + +
+ +