2023-07-24 20:56:10 +00:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"git.faercol.me/faercol/http-boot-server/bootserver/bootoption"
|
|
|
|
"git.faercol.me/faercol/http-boot-server/bootserver/helpers"
|
|
|
|
"git.faercol.me/faercol/http-boot-server/bootserver/services"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
const EnrollRoute = "/enroll"
|
|
|
|
|
|
|
|
type EnrollController struct {
|
|
|
|
clientService *services.ClientHandlerService
|
|
|
|
l *logrus.Logger
|
|
|
|
}
|
|
|
|
|
2023-07-24 21:05:50 +00:00
|
|
|
func NewEnrollController(l *logrus.Logger, service *services.ClientHandlerService) *EnrollController {
|
2023-07-24 20:56:10 +00:00
|
|
|
return &EnrollController{
|
2023-07-24 21:05:50 +00:00
|
|
|
clientService: service,
|
2023-07-24 20:56:10 +00:00
|
|
|
l: l,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ec *EnrollController) enrollMachine(w http.ResponseWriter, r *http.Request) (int, error) {
|
|
|
|
if r.Method != http.MethodPost {
|
|
|
|
return http.StatusMethodNotAllowed, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
dat, err := io.ReadAll(r.Body)
|
|
|
|
if err != nil {
|
|
|
|
return http.StatusInternalServerError, fmt.Errorf("failed to read body: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var client bootoption.Client
|
|
|
|
if err := json.Unmarshal(dat, &client); err != nil {
|
|
|
|
return http.StatusInternalServerError, fmt.Errorf("failed to parse body: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
ec.clientService.AddClient(&client)
|
2023-07-30 09:20:45 +00:00
|
|
|
ec.l.Infof("Added client")
|
2023-07-24 20:56:10 +00:00
|
|
|
return http.StatusAccepted, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ec *EnrollController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
returncode, err := ec.enrollMachine(w, r)
|
|
|
|
if err != nil {
|
|
|
|
ec.l.Errorf("Error handling client enrollement: %s", err.Error())
|
|
|
|
}
|
|
|
|
helpers.HandleResponse(w, r, returncode, nil, ec.l)
|
|
|
|
}
|