Files
arbeitszeitmessung/Backend/endpoints/time-create.go

69 lines
1.9 KiB
Go

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)
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())
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 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:]
}