package endpoints import ( "arbeitszeitmessung/helper" "arbeitszeitmessung/models" "encoding/json" "errors" "log" "net/http" ) // Relevant for arduino inputs -> creates new Booking from get and put method // GET only for demo purpose func TimeCreateHandler(w http.ResponseWriter, r *http.Request) { helper.SetCors(w) switch r.Method { case http.MethodPut: createBooking(w, r) break case http.MethodGet: createBooking(w, r) break case http.MethodOptions: // just support options header for non GET Requests from SWAGGER w.WriteHeader(http.StatusOK) break default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) break } } // Creates a booking from the http query params -> no body needed // after that entry wi'll be written to database and the booking is returned as json func createBooking(w http.ResponseWriter, r *http.Request) { if !checkPassword(r) { log.Println("Wrong or no API key provided!") http.Error(w, "Wrong or no API key provided", http.StatusUnauthorized) return } booking := (*models.Booking).FromUrlParams(nil, r.URL.Query()) if booking.Verify() { err := booking.Insert() if errors.Is(models.SameBookingError{}, err) { http.Error(w, "Booking already exists", http.StatusConflict) return } if err != nil { log.Println("Error inserting booking: ", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusAccepted) json.NewEncoder(w).Encode(booking) } w.WriteHeader(http.StatusBadRequest) } func checkPassword(r *http.Request) bool { authToken := helper.GetEnv("API_TOKEN", "dont_access") authHeaders := r.Header.Get("Authorization") _authStart := len("Bearer ") if len(authHeaders) <= _authStart { authHeaders = r.URL.Query().Get("api_key") _authStart = 0 if len(authHeaders) <= _authStart { return false } } return authToken == authHeaders[_authStart:] }