Introduce an API endpoint to exchange username to correctly-cased username and uuid

This commit is contained in:
ErickSkrauch 2024-09-22 15:28:03 +02:00
parent 5c84a47429
commit 8fbd295d46
No known key found for this signature in database
GPG Key ID: 669339FCBB30EE0E

40
main.go
View File

@ -2,6 +2,7 @@ package main
import ( import (
"database/sql" "database/sql"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@ -67,7 +68,12 @@ func main() {
db.SetMaxOpenConns(10) db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10) db.SetMaxIdleConns(10)
findAccountByUuidStmt, err := db.Prepare("SELECT username FROM accounts WHERE uuid = ? LIMIT 1") findUsernameByUuidStmt, err := db.Prepare("SELECT username FROM accounts WHERE uuid = ? LIMIT 1")
if err != nil {
panic(fmt.Errorf("unable to prepare query: %w", err))
}
findUuidAndCorrectUsernameByUsernameStmt, err := db.Prepare("SELECT uuid, username FROM accounts WHERE username = ? LIMIT 1")
if err != nil { if err != nil {
panic(fmt.Errorf("unable to prepare query: %w", err)) panic(fmt.Errorf("unable to prepare query: %w", err))
} }
@ -85,7 +91,7 @@ func main() {
} }
var username string var username string
err = findAccountByUuidStmt.QueryRow(uuid).Scan(&username) err = findUsernameByUuidStmt.QueryRow(uuid).Scan(&username)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
response.WriteHeader(204) response.WriteHeader(204)
return return
@ -124,6 +130,36 @@ func main() {
return return
} }
})) }))
router.GET("/api/mojang/profiles/:username", logRequestHandler(func(
response http.ResponseWriter,
request *http.Request,
params httprouter.Params,
) {
var username, uuid string
err = findUuidAndCorrectUsernameByUsernameStmt.QueryRow(params.ByName("username")).Scan(&uuid, &username)
if errors.Is(err, sql.ErrNoRows) {
response.WriteHeader(204)
return
} else if err != nil {
panic(err)
}
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(http.StatusOK)
result, err := json.Marshal(map[string]string{
"id": strings.ReplaceAll(uuid, "-", ""),
"name": username,
})
_, err = response.Write(result)
if err != nil {
sentry.CaptureException(fmt.Errorf("unable to write response body: %w", err))
response.WriteHeader(500)
return
}
}))
err = http.ListenAndServe(fmt.Sprintf("%s:%d", viper.GetString("http.host"), viper.GetInt("http.port")), router) err = http.ListenAndServe(fmt.Sprintf("%s:%d", viper.GetString("http.host"), viper.GetInt("http.port")), router)
if err != nil { if err != nil {