package Auth import ( "encoding/json" "io/ioutil" "log" "net/http" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/JsonSerialization" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" ) type signupResponse struct { Status string `json:"status"` Message string `json:"message"` } func makeSignupResponse(w http.ResponseWriter, code int, message string) { var ( status string = "error" returnJson []byte err error ) if code > 200 && code < 300 { status = "success" } returnJson, err = json.MarshalIndent(signupResponse{ Status: status, Message: message, }, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError) return } // Return updated json w.WriteHeader(code) w.Write(returnJson) } func Signup(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()) makeSignupResponse(w, http.StatusInternalServerError, "An error occurred") return } userData, err = JsonSerialization.DeserializeUser(requestBody, []string{ "id", }, false) if err != nil { log.Printf("Invalid data provided to Signup: %s\n", err.Error()) makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided") return } if userData.Username == "" || userData.Password == "" || userData.ConfirmPassword == "" || len(userData.AsymmetricPrivateKey) == 0 || len(userData.AsymmetricPublicKey) == 0 { makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided") return } err = Database.CheckUniqueUsername(userData.Username) if err != nil { makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided") return } userData.Password, err = HashPassword(userData.Password) if err != nil { makeSignupResponse(w, http.StatusInternalServerError, "An error occurred") return } err = Database.CreateUser(&userData) if err != nil { makeSignupResponse(w, http.StatusInternalServerError, "An error occurred") return } makeSignupResponse(w, http.StatusCreated, "Successfully signed up") }