You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.1 KiB

package Api
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/url"
"strconv"
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Api/JsonSerialization"
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
)
func getUsers(w http.ResponseWriter, r *http.Request) {
var (
users []Models.User
returnJson []byte
values url.Values
page, pageSize int
err error
)
values = r.URL.Query()
page, err = strconv.Atoi(values.Get("page"))
if err != nil {
log.Println("Could not parse page url argument")
JsonReturn(w, 500, "An error occured")
return
}
page, err = strconv.Atoi(values.Get("pageSize"))
if err != nil {
log.Println("Could not parse pageSize url argument")
JsonReturn(w, 500, "An error occured")
return
}
users, err = Database.GetUsers(page, pageSize)
if err != nil {
log.Printf("An error occured: %s\n", err.Error())
JsonReturn(w, 500, "An error occured")
return
}
returnJson, err = json.MarshalIndent(users, "", " ")
if err != nil {
JsonReturn(w, 500, "An error occured")
return
}
// Return updated json
w.WriteHeader(http.StatusOK)
w.Write(returnJson)
}
func createUser(w http.ResponseWriter, r *http.Request) {
var (
userData Models.User
requestBody []byte
err error
)
requestBody, err = ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error encountered reading POST body: %s\n", err.Error())
JsonReturn(w, 500, "An error occured")
return
}
userData, err = JsonSerialization.DeserializeUser(requestBody, []string{
"id",
"last_login",
}, false)
if err != nil {
log.Printf("Invalid data provided to user API: %s\n", err.Error())
JsonReturn(w, 405, "Invalid data")
return
}
err = Database.CheckUniqueEmail(userData.Email)
if err != nil {
JsonReturn(w, 405, "invalid_email")
return
}
if userData.Password != userData.ConfirmPassword {
JsonReturn(w, 500, "invalid_password")
return
}
err = Database.CreateUser(&userData)
if err != nil {
JsonReturn(w, 405, "Invalid data")
return
}
// Return updated json
w.WriteHeader(http.StatusOK)
}