41 lines
969 B
Go
41 lines
969 B
Go
package handlers
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/noderunners/nip05api/internal/user"
|
|
)
|
|
|
|
type Usernames struct{ Users *user.Service }
|
|
|
|
func (h *Usernames) Available(w http.ResponseWriter, r *http.Request) {
|
|
name := user.NormalizeUsername(chi.URLParam(r, "name"))
|
|
if err := user.ValidateUsername(name, h.Users.Reserved()); err != nil {
|
|
WriteJSON(w, http.StatusOK, map[string]any{
|
|
"username": name,
|
|
"available": false,
|
|
"reason": "invalid_or_reserved",
|
|
})
|
|
return
|
|
}
|
|
avail, err := h.Users.IsAvailable(r.Context(), name)
|
|
if err != nil {
|
|
if errors.Is(err, user.ErrInvalidUsername) {
|
|
WriteJSON(w, http.StatusOK, map[string]any{
|
|
"username": name,
|
|
"available": false,
|
|
"reason": "invalid",
|
|
})
|
|
return
|
|
}
|
|
WriteError(w, http.StatusInternalServerError, "InternalError", err.Error())
|
|
return
|
|
}
|
|
WriteJSON(w, http.StatusOK, map[string]any{
|
|
"username": name,
|
|
"available": avail,
|
|
})
|
|
}
|