2020-04-19 05:01:09 +05:30
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
|
2024-02-01 12:28:26 +05:30
|
|
|
"github.com/elyby/chrly/internal/db"
|
2024-01-30 13:35:04 +05:30
|
|
|
"github.com/elyby/chrly/internal/profiles"
|
2020-04-19 05:01:09 +05:30
|
|
|
)
|
|
|
|
|
2024-01-30 13:35:04 +05:30
|
|
|
type ProfilesManager interface {
|
|
|
|
PersistProfile(profile *db.Profile) error
|
|
|
|
RemoveProfileByUuid(uuid string) error
|
2020-04-19 05:01:09 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
type Api struct {
|
2024-01-30 13:35:04 +05:30
|
|
|
ProfilesManager
|
2020-04-19 05:01:09 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
func (ctx *Api) Handler() *mux.Router {
|
|
|
|
router := mux.NewRouter().StrictSlash(true)
|
2024-01-30 13:35:04 +05:30
|
|
|
router.HandleFunc("/profiles", ctx.postProfileHandler).Methods(http.MethodPost)
|
|
|
|
router.HandleFunc("/profiles/{uuid}", ctx.deleteProfileByUuidHandler).Methods(http.MethodDelete)
|
2020-04-19 05:01:09 +05:30
|
|
|
|
|
|
|
return router
|
|
|
|
}
|
|
|
|
|
2024-01-30 13:35:04 +05:30
|
|
|
func (ctx *Api) postProfileHandler(resp http.ResponseWriter, req *http.Request) {
|
|
|
|
err := req.ParseForm()
|
|
|
|
if err != nil {
|
|
|
|
apiBadRequest(resp, map[string][]string{
|
|
|
|
"body": {"The body of the request must be a valid url-encoded string"},
|
|
|
|
})
|
2020-04-19 05:01:09 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-01-30 13:35:04 +05:30
|
|
|
profile := &db.Profile{
|
|
|
|
Uuid: req.Form.Get("uuid"),
|
|
|
|
Username: req.Form.Get("username"),
|
|
|
|
SkinUrl: req.Form.Get("skinUrl"),
|
|
|
|
SkinModel: req.Form.Get("skinModel"),
|
|
|
|
CapeUrl: req.Form.Get("capeUrl"),
|
|
|
|
MojangTextures: req.Form.Get("mojangTextures"),
|
|
|
|
MojangSignature: req.Form.Get("mojangSignature"),
|
2020-04-19 05:01:09 +05:30
|
|
|
}
|
|
|
|
|
2024-01-30 13:35:04 +05:30
|
|
|
err = ctx.PersistProfile(profile)
|
|
|
|
if err != nil {
|
|
|
|
var v *profiles.ValidationError
|
|
|
|
if errors.As(err, &v) {
|
|
|
|
apiBadRequest(resp, v.Errors)
|
|
|
|
return
|
2020-04-20 17:46:15 +05:30
|
|
|
}
|
2020-04-19 05:01:09 +05:30
|
|
|
|
2024-01-30 13:35:04 +05:30
|
|
|
apiServerError(resp, "Unable to save profile to db", err)
|
|
|
|
return
|
2020-04-19 05:01:09 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
resp.WriteHeader(http.StatusCreated)
|
|
|
|
}
|
|
|
|
|
2024-01-30 13:35:04 +05:30
|
|
|
func (ctx *Api) deleteProfileByUuidHandler(resp http.ResponseWriter, req *http.Request) {
|
|
|
|
uuid := mux.Vars(req)["uuid"]
|
|
|
|
err := ctx.ProfilesManager.RemoveProfileByUuid(uuid)
|
2020-04-19 05:01:09 +05:30
|
|
|
if err != nil {
|
2024-01-30 13:35:04 +05:30
|
|
|
apiServerError(resp, "Unable to delete profile from db", err)
|
2020-04-19 05:01:09 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
resp.WriteHeader(http.StatusNoContent)
|
|
|
|
}
|