spaceapid/handlers/util.go
Bendodroid 38710484f9
Generate HTTP endpoints for environment sensors
- Move update request sanity checks to new method in handlers/util.go
- Change EnvironmentSensor.Value type because ParseFloat returns float64
2024-01-14 01:10:38 +01:00

46 lines
1.3 KiB
Go

package handlers
import (
"io"
"log"
"net/http"
"gitlab.hamburg.ccc.de/ccchh/spaceapid/config"
"gitlab.hamburg.ccc.de/ccchh/spaceapid/util"
)
// updateEndpointValidator checks BasicAuth credentials,
// checks for correct HTTP method and then returns the request body
func updateEndpointValidator(
authDB config.HTTPBACredentials, validCredentials []config.HTTPBACredentialID,
w http.ResponseWriter, r *http.Request,
) (body []byte) {
// Check BasicAuth credentials
username, password, ok := r.BasicAuth()
if !ok || !util.CheckCredentials(authDB, validCredentials, username, password) {
log.Println("Unauthorized request from", r.RemoteAddr)
w.Header().Set("WWW-Authenticate", "Basic realm=\"space-api\"")
w.WriteHeader(http.StatusUnauthorized)
return
}
// Check if PUT method
if r.Method != http.MethodPut {
log.Println("Wrong Method: ", r.Method, "from", r.RemoteAddr, "at", r.RequestURI)
w.Header().Set("Allow", http.MethodPut)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
// Read request body
body, err := io.ReadAll(r.Body)
if err != nil {
log.Println("Failed to read request body from", r.RemoteAddr)
w.WriteHeader(http.StatusInternalServerError)
_, _ = io.WriteString(w, "Failed reading HTTP request body")
return
}
return
}