{ "username": "asdf" } result: { code: 204 }
(app *App, w http.ResponseWriter, r *http.Request)
| 72 | // { "username": "asdf" } |
| 73 | // result: { code: 204 } |
| 74 | func handleUsernameCheck(app *App, w http.ResponseWriter, r *http.Request) error { |
| 75 | reqJSON := IsJSON(r) |
| 76 | |
| 77 | // Get params |
| 78 | var d struct { |
| 79 | Username string `json:"username"` |
| 80 | } |
| 81 | if reqJSON { |
| 82 | decoder := json.NewDecoder(r.Body) |
| 83 | err := decoder.Decode(&d) |
| 84 | if err != nil { |
| 85 | log.Error("Couldn't decode username check: %v\n", err) |
| 86 | return ErrBadFormData |
| 87 | } |
| 88 | } else { |
| 89 | return impart.HTTPError{http.StatusNotAcceptable, "Must be JSON request"} |
| 90 | } |
| 91 | |
| 92 | // Check if username is okay |
| 93 | finalUsername := getSlug(d.Username, "") |
| 94 | if finalUsername == "" { |
| 95 | errMsg := "Invalid username" |
| 96 | if d.Username != "" { |
| 97 | // Username was provided, but didn't convert into valid latin characters |
| 98 | errMsg += " - must have at least 2 letters or numbers" |
| 99 | } |
| 100 | return impart.HTTPError{http.StatusBadRequest, errMsg + "."} |
| 101 | } |
| 102 | if app.db.PostIDExists(finalUsername) { |
| 103 | return impart.HTTPError{http.StatusConflict, "Username is already taken."} |
| 104 | } |
| 105 | var un string |
| 106 | err := app.db.QueryRow("SELECT username FROM users WHERE username = ?", finalUsername).Scan(&un) |
| 107 | switch { |
| 108 | case err == sql.ErrNoRows: |
| 109 | return impart.WriteSuccess(w, finalUsername, http.StatusOK) |
| 110 | case err != nil: |
| 111 | log.Error("Couldn't SELECT username: %v", err) |
| 112 | return impart.HTTPError{http.StatusInternalServerError, "We messed up."} |
| 113 | } |
| 114 | |
| 115 | // Username was found, so it's taken |
| 116 | return impart.HTTPError{http.StatusConflict, "Username is already taken."} |
| 117 | } |
| 118 | |
| 119 | func getValidUsername(app *App, reqName, prevName string) (string, *impart.HTTPError) { |
| 120 | // Check if username is okay |
nothing calls this directly
no test coverage detected