package api import ( "net/http" userAuth "forge.cadoles.com/Cadoles/emissary/internal/auth/user" "forge.cadoles.com/Cadoles/emissary/internal/datastore" "github.com/pkg/errors" "gitlab.com/wpetit/goweb/api" "gitlab.com/wpetit/goweb/logger" ) func (m *Mount) queryAgents(w http.ResponseWriter, r *http.Request) { baseUser, ok := assertRequestUser(w, r) if !ok { return } ctx := r.Context() user, ok := baseUser.(*userAuth.User) if !ok { logger.Error(ctx, "unexpected user type", logger.F("user", baseUser)) api.ErrorResponse(w, http.StatusInternalServerError, ErrCodeUnknownError, nil) return } limit, ok := getIntQueryParam(w, r, "limit", 10) if !ok { return } offset, ok := getIntQueryParam(w, r, "offset", 0) if !ok { return } options := []datastore.AgentQueryOptionFunc{ datastore.WithAgentQueryLimit(int(limit)), datastore.WithAgentQueryOffset(int(offset)), } if user.Role() != userAuth.RoleAdmin { options = append(options, datastore.WithAgentQueryTenantID(user.Tenant())) } ids, ok := getIntSliceValues(w, r, "ids", nil) if !ok { return } if ids != nil { agentIDs := func(ids []int64) []datastore.AgentID { agentIDs := make([]datastore.AgentID, 0, len(ids)) for _, id := range ids { agentIDs = append(agentIDs, datastore.AgentID(id)) } return agentIDs }(ids) options = append(options, datastore.WithAgentQueryID(agentIDs...)) } thumbprints, ok := getStringSliceValues(w, r, "thumbprints", nil) if !ok { return } if thumbprints != nil { options = append(options, datastore.WithAgentQueryThumbprints(thumbprints...)) } statuses, ok := getIntSliceValues(w, r, "statuses", nil) if !ok { return } if statuses != nil { agentStatuses := func(statuses []int64) []datastore.AgentStatus { agentStatuses := make([]datastore.AgentStatus, 0, len(statuses)) for _, status := range statuses { agentStatuses = append(agentStatuses, datastore.AgentStatus(status)) } return agentStatuses }(statuses) options = append(options, datastore.WithAgentQueryStatus(agentStatuses...)) } agents, total, err := m.agentRepo.Query( ctx, options..., ) if err != nil { err = errors.WithStack(err) logger.Error(ctx, "could not list agents", logger.CapturedE(err)) api.ErrorResponse(w, http.StatusInternalServerError, ErrCodeUnknownError, nil) return } api.DataResponse(w, http.StatusOK, struct { Agents []*datastore.Agent `json:"agents"` Total int `json:"total"` }{ Agents: agents, Total: total, }) }