2023-11-05 20:23:31 +01:00
|
|
|
package handlers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
2024-01-13 23:26:04 +01:00
|
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/config"
|
2023-11-05 20:23:31 +01:00
|
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/types"
|
2024-01-13 23:26:04 +01:00
|
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/util"
|
2023-11-05 20:23:31 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func StateOpen(
|
2024-01-13 23:26:04 +01:00
|
|
|
authDB config.HTTPBACredentials, validCredentials []config.HTTPBACredentialID,
|
|
|
|
resp *types.SpaceAPIResponseV14,
|
2023-11-05 20:23:31 +01:00
|
|
|
) func(http.ResponseWriter, *http.Request) {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
// Check BasicAuth credentials
|
|
|
|
username, password, ok := r.BasicAuth()
|
2024-01-13 23:26:04 +01:00
|
|
|
if !ok || !util.CheckCredentials(authDB, validCredentials, username, password) {
|
2023-11-05 20:23:31 +01:00
|
|
|
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 from", r.RemoteAddr)
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
// Parse request body
|
|
|
|
newState, err := strconv.ParseBool(string(body))
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Failed to parse request body from", r.RemoteAddr)
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
_, _ = io.WriteString(w, "HTTP request body should either be true or false")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set SpaceAPI response values
|
|
|
|
resp.State.Open = newState
|
|
|
|
resp.State.LastChange = time.Now().Unix()
|
|
|
|
|
|
|
|
// Respond with OK
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
_, _ = io.WriteString(w, "Update Successful")
|
|
|
|
}
|
|
|
|
}
|