|
| 1 | +package validation |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + |
| 8 | + "github.com/stackitcloud/stackit-cli/internal/pkg/errors" |
| 9 | + "github.com/stackitcloud/stackit-cli/internal/pkg/print" |
| 10 | + "github.com/stackitcloud/stackit-cli/internal/pkg/projectname" |
| 11 | + "github.com/stackitcloud/stackit-cli/internal/pkg/services/resourcemanager/client" |
| 12 | + |
| 13 | + "github.com/spf13/cobra" |
| 14 | + "github.com/stackitcloud/stackit-sdk-go/core/oapierror" |
| 15 | +) |
| 16 | + |
| 17 | +// ValidateProject validates that the project ID is not empty, exists, and the user has access to it. |
| 18 | +// It returns the project name for display purposes. |
| 19 | +func ValidateProject(ctx context.Context, p *print.Printer, cliVersion string, cmd *cobra.Command, projectId string) (string, error) { |
| 20 | + // Check if project ID is empty |
| 21 | + if projectId == "" { |
| 22 | + return "", &errors.ProjectIdError{} |
| 23 | + } |
| 24 | + |
| 25 | + // Configure Resource Manager API client |
| 26 | + apiClient, err := client.ConfigureClient(p, cliVersion) |
| 27 | + if err != nil { |
| 28 | + return "", fmt.Errorf("configure resource manager client: %w", err) |
| 29 | + } |
| 30 | + |
| 31 | + // Try to get project details to validate existence and access |
| 32 | + req := apiClient.GetProject(ctx, projectId) |
| 33 | + resp, err := req.Execute() |
| 34 | + if err != nil { |
| 35 | + // Check for specific HTTP status codes |
| 36 | + if httpErr, ok := err.(*oapierror.GenericOpenAPIError); ok { |
| 37 | + switch httpErr.StatusCode { |
| 38 | + case http.StatusNotFound: |
| 39 | + // Try to get project name for better error message |
| 40 | + projectLabel := projectId |
| 41 | + if projectName, nameErr := projectname.GetProjectName(ctx, p, cliVersion, cmd); nameErr == nil { |
| 42 | + projectLabel = projectName |
| 43 | + } |
| 44 | + return "", &errors.ProjectNotFoundError{ProjectId: projectId, ProjectLabel: projectLabel} |
| 45 | + case http.StatusForbidden: |
| 46 | + // Try to get project name for better error message |
| 47 | + projectLabel := projectId |
| 48 | + if projectName, nameErr := projectname.GetProjectName(ctx, p, cliVersion, cmd); nameErr == nil { |
| 49 | + projectLabel = projectName |
| 50 | + } |
| 51 | + return "", &errors.ProjectAccessDeniedError{ProjectId: projectId, ProjectLabel: projectLabel} |
| 52 | + case http.StatusUnauthorized: |
| 53 | + return "", &errors.AuthError{} |
| 54 | + } |
| 55 | + } |
| 56 | + return "", fmt.Errorf("validate project: %w", err) |
| 57 | + } |
| 58 | + |
| 59 | + // Project exists and user has access, returning the project name |
| 60 | + return *resp.Name, nil |
| 61 | +} |
0 commit comments