http-boot-server/bootserver/controllers/client/enroll.go

69 lines
1.8 KiB
Go
Raw Permalink Normal View History

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 newClientPayload struct {
ID string `json:"ID"`
}
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 {
return &EnrollController{
2023-07-24 21:05:50 +00:00
clientService: service,
l: l,
}
}
func (ec *EnrollController) enrollMachine(w http.ResponseWriter, r *http.Request) (int, []byte, error) {
if r.Method != http.MethodPost {
return http.StatusMethodNotAllowed, nil, nil
}
dat, err := io.ReadAll(r.Body)
if err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf("failed to read body: %w", err)
}
var client bootoption.Client
if err := json.Unmarshal(dat, &client); err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf("failed to parse body: %w", err)
}
cltID, err := ec.clientService.AddClient(&client)
if err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf("failed to create client %w", err)
}
payload, err := json.Marshal(newClientPayload{ID: cltID.String()})
if err != nil {
return http.StatusInternalServerError, nil, fmt.Errorf("failed to serialize payload: %w", err)
}
2023-07-30 09:20:45 +00:00
ec.l.Infof("Added client")
return http.StatusOK, payload, nil
}
func (ec *EnrollController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
returncode, content, err := ec.enrollMachine(w, r)
if err != nil {
ec.l.Errorf("Error handling client enrollement: %s", err.Error())
}
helpers.HandleResponse(w, r, returncode, content, ec.l)
}