Encrypted messaging app
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.

95 lines
2.2 KiB

  1. package Auth
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "log"
  6. "net/http"
  7. "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/JsonSerialization"
  8. "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
  9. "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
  10. )
  11. type signupResponse struct {
  12. Status string `json:"status"`
  13. Message string `json:"message"`
  14. }
  15. func makeSignupResponse(w http.ResponseWriter, code int, message string) {
  16. var (
  17. status string = "error"
  18. returnJson []byte
  19. err error
  20. )
  21. if code > 200 && code < 300 {
  22. status = "success"
  23. }
  24. returnJson, err = json.MarshalIndent(signupResponse{
  25. Status: status,
  26. Message: message,
  27. }, "", " ")
  28. if err != nil {
  29. http.Error(w, "Error", http.StatusInternalServerError)
  30. return
  31. }
  32. // Return updated json
  33. w.WriteHeader(code)
  34. w.Write(returnJson)
  35. }
  36. func Signup(w http.ResponseWriter, r *http.Request) {
  37. var (
  38. userData Models.User
  39. requestBody []byte
  40. err error
  41. )
  42. requestBody, err = ioutil.ReadAll(r.Body)
  43. if err != nil {
  44. log.Printf("Error encountered reading POST body: %s\n", err.Error())
  45. makeSignupResponse(w, http.StatusInternalServerError, "An error occurred")
  46. return
  47. }
  48. userData, err = JsonSerialization.DeserializeUser(requestBody, []string{
  49. "id",
  50. }, false)
  51. if err != nil {
  52. log.Printf("Invalid data provided to Signup: %s\n", err.Error())
  53. makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided")
  54. return
  55. }
  56. if userData.Username == "" ||
  57. userData.Password == "" ||
  58. userData.ConfirmPassword == "" ||
  59. len(userData.AsymmetricPrivateKey) == 0 ||
  60. len(userData.AsymmetricPublicKey) == 0 {
  61. makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided")
  62. return
  63. }
  64. err = Database.CheckUniqueUsername(userData.Username)
  65. if err != nil {
  66. makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided")
  67. return
  68. }
  69. userData.Password, err = HashPassword(userData.Password)
  70. if err != nil {
  71. makeSignupResponse(w, http.StatusInternalServerError, "An error occurred")
  72. return
  73. }
  74. err = Database.CreateUser(&userData)
  75. if err != nil {
  76. makeSignupResponse(w, http.StatusInternalServerError, "An error occurred")
  77. return
  78. }
  79. makeSignupResponse(w, http.StatusCreated, "Successfully signed up")
  80. }