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) queryTenants(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.TenantQueryOptionFunc{ datastore.WithTenantQueryLimit(int(limit)), datastore.WithTenantQueryOffset(int(offset)), } ids, ok := getStringSliceValues(w, r, "ids", nil) if !ok { return } tenantIDs := make([]datastore.TenantID, 0) if user.Role() != userAuth.RoleAdmin { tenantIDs = append(tenantIDs, user.Tenant()) } for _, id := range ids { tenantIDs = append(tenantIDs, datastore.TenantID(id)) } if len(tenantIDs) > 0 { options = append(options, datastore.WithTenantQueryID(tenantIDs...)) } tenants, total, err := m.tenantRepo.Query( ctx, options..., ) if err != nil { err = errors.WithStack(err) logger.Error(ctx, "could not list tenants", logger.CapturedE(err)) api.ErrorResponse(w, http.StatusInternalServerError, ErrCodeUnknownError, nil) return } api.DataResponse(w, http.StatusOK, struct { Tenants []*datastore.Tenant `json:"tenants"` Total int `json:"total"` }{ Tenants: tenants, Total: total, }) }