package api import ( "net/http" "forge.cadoles.com/Cadoles/emissary/internal/datastore" "github.com/pkg/errors" "gitlab.com/wpetit/goweb/api" "gitlab.com/wpetit/goweb/logger" ) type claimAgentRequest struct { Thumbprint string `json:"thumbprint" validate:"required"` } func (m *Mount) claimAgent(w http.ResponseWriter, r *http.Request) { user, ok := assertRequestUser(w, r) if !ok { return } ctx := r.Context() claimAgentReq := &claimAgentRequest{} if ok := api.Bind(w, r, claimAgentReq); !ok { return } results, _, err := m.agentRepo.Query( ctx, datastore.WithAgentQueryThumbprints(claimAgentReq.Thumbprint), ) if err != nil { err = errors.WithStack(err) logger.Error(ctx, "could not query agents", logger.CapturedE(err)) api.ErrorResponse(w, http.StatusInternalServerError, ErrCodeUnknownError, nil) return } if len(results) == 0 { api.ErrorResponse(w, http.StatusNotFound, ErrCodeNotFound, nil) return } if len(results) > 1 { logger.Error(ctx, "multiple results for agent thumbprint", logger.F("agentThumbprint", claimAgentReq.Thumbprint)) api.ErrorResponse(w, http.StatusInternalServerError, ErrCodeMultipleResults, nil) return } agent := results[0] if agent.TenantID != nil { logger.Error(ctx, "agent already claimed", logger.F("agentThumbprint", claimAgentReq.Thumbprint), logger.F("agentID", agent.ID), logger.F("tenantID", agent.TenantID)) api.ErrorResponse(w, http.StatusConflict, ErrCodeAlreadyClaimed, nil) return } agent, err = m.agentRepo.Attach(ctx, user.Tenant(), agent.ID) if err != nil { err = errors.WithStack(err) logger.Error(ctx, "could not attach agent", logger.CapturedE(err)) api.ErrorResponse(w, http.StatusInternalServerError, ErrCodeUnknownError, nil) return } api.DataResponse(w, http.StatusOK, struct { Agent *datastore.Agent `json:"agent"` }{ Agent: agent, }) }