2021-11-25 03:59:51 +00:00
|
|
|
package website
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"git.handmade.network/hmn/hmn/src/db"
|
|
|
|
"git.handmade.network/hmn/hmn/src/models"
|
|
|
|
"git.handmade.network/hmn/hmn/src/oops"
|
|
|
|
)
|
|
|
|
|
|
|
|
func APICheckUsername(c *RequestContext) ResponseData {
|
|
|
|
c.Req.ParseForm()
|
|
|
|
usernameArgs, hasUsername := c.Req.Form["username"]
|
|
|
|
found := false
|
|
|
|
canonicalUsername := ""
|
|
|
|
if hasUsername {
|
|
|
|
requestedUsername := usernameArgs[0]
|
|
|
|
found = true
|
|
|
|
c.Perf.StartBlock("SQL", "Fetch user")
|
2022-04-16 17:49:29 +00:00
|
|
|
user, err := db.QueryOne[models.User](c.Context(), c.Conn,
|
2021-11-25 03:59:51 +00:00
|
|
|
`
|
2022-04-16 17:49:29 +00:00
|
|
|
SELECT $columns{auth_user}
|
2021-11-25 03:59:51 +00:00
|
|
|
FROM
|
|
|
|
auth_user
|
2021-12-29 14:38:23 +00:00
|
|
|
LEFT JOIN handmade_asset AS auth_user_avatar ON auth_user_avatar.id = auth_user.avatar_asset_id
|
2021-11-25 03:59:51 +00:00
|
|
|
WHERE
|
|
|
|
LOWER(auth_user.username) = LOWER($1)
|
|
|
|
AND status = ANY ($2)
|
|
|
|
`,
|
|
|
|
requestedUsername,
|
|
|
|
[]models.UserStatus{models.UserStatusConfirmed, models.UserStatusApproved},
|
|
|
|
)
|
|
|
|
c.Perf.EndBlock()
|
|
|
|
if err != nil {
|
|
|
|
if errors.Is(err, db.NotFound) {
|
|
|
|
found = false
|
|
|
|
} else {
|
|
|
|
return c.ErrorResponse(http.StatusInternalServerError, oops.New(err, "failed to fetch user: %s", requestedUsername))
|
|
|
|
}
|
|
|
|
} else {
|
2022-04-16 17:49:29 +00:00
|
|
|
canonicalUsername = user.Username
|
2021-11-25 03:59:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var res ResponseData
|
|
|
|
res.Header().Set("Content-Type", "application/json")
|
2021-12-04 14:55:45 +00:00
|
|
|
AddCORSHeaders(c, &res)
|
2021-11-25 03:59:51 +00:00
|
|
|
if found {
|
|
|
|
res.Write([]byte(fmt.Sprintf(`{ "found": true, "canonical": "%s" }`, canonicalUsername)))
|
|
|
|
} else {
|
|
|
|
res.Write([]byte(`{ "found": false }`))
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|