spaceapid/handlers/util.go

43 lines
1.4 KiB
Go

package handlers
import (
"errors"
"fmt"
"io"
"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,
) ([]byte, error) {
// Check BasicAuth credentials
username, password, ok := r.BasicAuth()
if !ok || !util.CheckCredentials(authDB, validCredentials, username, password) {
w.Header()["WWW-Authenticate"] = []string{"Basic realm=\"spaceapid\""}
http.Error(w, "", http.StatusUnauthorized)
return []byte{}, errors.New(fmt.Sprintf("Unauthorized request from %s Username: %s Password: %s", r.RemoteAddr, username, password))
}
// Check if PUT method
if r.Method != http.MethodPut {
w.Header().Set("Allow", http.MethodPut)
http.Error(w, "", http.StatusMethodNotAllowed)
return []byte{}, errors.New(fmt.Sprintf("Wrong Method: %s from %s at %s", r.Method, r.RemoteAddr, r.RequestURI))
}
// Read request body
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return []byte{}, errors.New(fmt.Sprintf("Failed to read request body from %s with error: %s", r.RemoteAddr, err))
}
return body, nil
}