|
| 1 | +package configure |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/vngcloud/greennode-cli/internal/auth" |
| 11 | + "github.com/vngcloud/greennode-cli/internal/config" |
| 12 | +) |
| 13 | + |
| 14 | +// vserverEndpointForRegion returns the vServer base URL for a region, |
| 15 | +// looking it up in the REGIONS map. |
| 16 | +func vserverEndpointForRegion(region string) (string, error) { |
| 17 | + r, ok := config.REGIONS[region] |
| 18 | + if !ok { |
| 19 | + return "", fmt.Errorf("unknown region: %s", region) |
| 20 | + } |
| 21 | + ep, ok := r["vserver_endpoint"] |
| 22 | + if !ok { |
| 23 | + return "", fmt.Errorf("no vserver_endpoint configured for region %s", region) |
| 24 | + } |
| 25 | + return ep, nil |
| 26 | +} |
| 27 | + |
| 28 | +// detectProjectTimeout is short — configure should fail fast, not hang the wizard. |
| 29 | +const detectProjectTimeout = 10 * time.Second |
| 30 | + |
| 31 | +type projectsResponse struct { |
| 32 | + Projects []struct { |
| 33 | + ProjectID string `json:"projectId"` |
| 34 | + } `json:"projects"` |
| 35 | +} |
| 36 | + |
| 37 | +// detectProjectID fetches the caller's project from vServer /v1/projects |
| 38 | +// using the given credentials and region's vServer endpoint. |
| 39 | +// |
| 40 | +// Returns the first projectId. Each user is expected to have exactly one |
| 41 | +// project per region; returning the first is safe by that contract. |
| 42 | +func detectProjectID(clientID, clientSecret, vserverEndpoint string) (string, error) { |
| 43 | + tm := auth.NewTokenManager(clientID, clientSecret) |
| 44 | + token, err := tm.GetToken() |
| 45 | + if err != nil { |
| 46 | + return "", fmt.Errorf("authentication failed: %w", err) |
| 47 | + } |
| 48 | + |
| 49 | + req, err := http.NewRequest("GET", vserverEndpoint+"/v1/projects", nil) |
| 50 | + if err != nil { |
| 51 | + return "", err |
| 52 | + } |
| 53 | + req.Header.Set("Authorization", "Bearer "+token) |
| 54 | + |
| 55 | + httpClient := &http.Client{Timeout: detectProjectTimeout} |
| 56 | + resp, err := httpClient.Do(req) |
| 57 | + if err != nil { |
| 58 | + return "", fmt.Errorf("failed to fetch projects: %w", err) |
| 59 | + } |
| 60 | + defer resp.Body.Close() |
| 61 | + |
| 62 | + if resp.StatusCode != http.StatusOK { |
| 63 | + body, _ := io.ReadAll(resp.Body) |
| 64 | + return "", fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body)) |
| 65 | + } |
| 66 | + |
| 67 | + var parsed projectsResponse |
| 68 | + if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil { |
| 69 | + return "", fmt.Errorf("failed to parse response: %w", err) |
| 70 | + } |
| 71 | + |
| 72 | + if len(parsed.Projects) == 0 { |
| 73 | + return "", fmt.Errorf("account has no project in this region") |
| 74 | + } |
| 75 | + |
| 76 | + return parsed.Projects[0].ProjectID, nil |
| 77 | +} |
0 commit comments