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

  1. package Api
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "log"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Api/JsonSerialization"
  10. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
  11. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
  12. )
  13. func getUsers(w http.ResponseWriter, r *http.Request) {
  14. var (
  15. users []Models.User
  16. returnJson []byte
  17. values url.Values
  18. page, pageSize int
  19. err error
  20. )
  21. values = r.URL.Query()
  22. page, err = strconv.Atoi(values.Get("page"))
  23. if err != nil {
  24. log.Println("Could not parse page url argument")
  25. JsonReturn(w, 500, "An error occured")
  26. return
  27. }
  28. page, err = strconv.Atoi(values.Get("pageSize"))
  29. if err != nil {
  30. log.Println("Could not parse pageSize url argument")
  31. JsonReturn(w, 500, "An error occured")
  32. return
  33. }
  34. users, err = Database.GetUsers(page, pageSize)
  35. if err != nil {
  36. log.Printf("An error occured: %s\n", err.Error())
  37. JsonReturn(w, 500, "An error occured")
  38. return
  39. }
  40. returnJson, err = json.MarshalIndent(users, "", " ")
  41. if err != nil {
  42. JsonReturn(w, 500, "An error occured")
  43. return
  44. }
  45. // Return updated json
  46. w.WriteHeader(http.StatusOK)
  47. w.Write(returnJson)
  48. }
  49. func createUser(w http.ResponseWriter, r *http.Request) {
  50. var (
  51. userData Models.User
  52. requestBody []byte
  53. err error
  54. )
  55. requestBody, err = ioutil.ReadAll(r.Body)
  56. if err != nil {
  57. log.Printf("Error encountered reading POST body: %s\n", err.Error())
  58. JsonReturn(w, 500, "An error occured")
  59. return
  60. }
  61. userData, err = JsonSerialization.DeserializeUser(requestBody, []string{
  62. "id",
  63. "last_login",
  64. }, false)
  65. if err != nil {
  66. log.Printf("Invalid data provided to user API: %s\n", err.Error())
  67. JsonReturn(w, 405, "Invalid data")
  68. return
  69. }
  70. err = Database.CheckUniqueEmail(userData.Email)
  71. if err != nil {
  72. JsonReturn(w, 405, "invalid_email")
  73. return
  74. }
  75. if userData.Password != userData.ConfirmPassword {
  76. JsonReturn(w, 500, "invalid_password")
  77. return
  78. }
  79. err = Database.CreateUser(&userData)
  80. if err != nil {
  81. JsonReturn(w, 405, "Invalid data")
  82. return
  83. }
  84. // Return updated json
  85. w.WriteHeader(http.StatusOK)
  86. }