Files
arbeitszeitmessung/Backend/endpoints/time-create.go
Tom Tröger ba034f1c33
Some checks failed
Tests / Run Go Tests (push) Failing after 1m35s
Arbeitszeitmessung Deploy / Build Webserver (push) Successful in 2m48s
feat: updated docs and added description to files
2026-01-29 18:28:28 +01:00

75 lines
2.1 KiB
Go

package endpoints
// this endpoint served at "/time/create" is for the esp api and creates bookings
// either via HTTP GET or HTTP PUT
import (
"arbeitszeitmessung/helper"
"arbeitszeitmessung/models"
"encoding/json"
"errors"
"log"
"net/http"
"time"
)
// 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)
case http.MethodGet:
createBooking(w, r)
case http.MethodOptions:
// just support options header for non GET Requests from SWAGGER
w.WriteHeader(http.StatusOK)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
// 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 !verifyToken(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())
booking.Timestamp = time.Now()
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)
return
}
http.Error(w, "Cannot verify booking, maybe missing a parameter", http.StatusBadRequest)
}
func verifyToken(r *http.Request) bool {
authToken := helper.GetEnv("API_TOKEN", "dont_access")
authHeaders := r.Header.Get("Authorization")
if len(authHeaders) <= 7 { //len "Bearer "
authHeaders = r.URL.Query().Get("api_key")
if len(authHeaders) <= 0 {
return false
}
return authToken == authHeaders
}
return authToken == authHeaders[7:]
}