Bendodroid
b2f62c7bb0
- Functionally equivalent to old version at present - Temperature and Humidity sensors not handled yet - Moved HTTP handlers around
64 lines
1.7 KiB
Go
64 lines
1.7 KiB
Go
package handlers
|
|
|
|
import (
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/config"
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/types"
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/util"
|
|
)
|
|
|
|
func StateOpen(
|
|
authDB config.HTTPBACredentials, validCredentials []config.HTTPBACredentialID,
|
|
resp *types.SpaceAPIResponseV14,
|
|
) func(http.ResponseWriter, *http.Request) {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
// 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 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")
|
|
}
|
|
}
|