diff --git a/auth/set_org.go b/auth/set_org.go index 0d929ff..090f461 100644 --- a/auth/set_org.go +++ b/auth/set_org.go @@ -2,9 +2,12 @@ package auth import ( "context" + "fmt" + "slices" "github.com/ninech/nctl/api" "github.com/ninech/nctl/api/config" + "github.com/ninech/nctl/internal/format" ) type SetOrgCmd struct { @@ -20,5 +23,19 @@ func (s *SetOrgCmd) Run(ctx context.Context, client *api.Client) error { return whoamicmd.Run(ctx, client) } - return config.SetContextOrganization(client.KubeconfigPath, client.KubeconfigContext, s.Organization) + userInfo, err := api.GetUserInfoFromToken(client.Token(ctx)) + if err != nil { + return err + } + + if err := config.SetContextOrganization(client.KubeconfigPath, client.KubeconfigContext, s.Organization); err != nil { + return err + } + + if !slices.Contains(userInfo.Orgs, s.Organization) { + format.PrintWarningf("%s is not in list of available Organizations, you might not have access to all resources.\n", s.Organization) + } + + fmt.Println(format.SuccessMessagef("📝", "set active Organization to %s", s.Organization)) + return nil } diff --git a/auth/set_project.go b/auth/set_project.go index 83b39f4..978d594 100644 --- a/auth/set_project.go +++ b/auth/set_project.go @@ -2,9 +2,14 @@ package auth import ( "context" + "fmt" + management "github.com/ninech/apis/management/v1alpha1" "github.com/ninech/nctl/api" "github.com/ninech/nctl/api/config" + "github.com/ninech/nctl/internal/format" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" ) type SetProjectCmd struct { @@ -12,5 +17,29 @@ type SetProjectCmd struct { } func (s *SetProjectCmd) Run(ctx context.Context, client *api.Client) error { - return config.SetContextProject(client.KubeconfigPath, client.KubeconfigContext, s.Name) + org, err := client.Organization() + if err != nil { + return err + } + + // we get the project without using the result to be sure it exists and the + // user has access. + if err := client.Get(ctx, types.NamespacedName{Name: s.Name, Namespace: org}, &management.Project{}); err != nil { + if !errors.IsNotFound(err) && !errors.IsForbidden(err) { + return err + } + if errors.IsNotFound(err) { + format.PrintWarningf("did not find Project %s in your Organization %s.\n", s.Name, org) + } + if errors.IsForbidden(err) { + format.PrintWarningf("you are not allowed to get the Project %s, you might not have access to all resources.\n", s.Name) + } + } + + if err := config.SetContextProject(client.KubeconfigPath, client.KubeconfigContext, s.Name); err != nil { + return err + } + + fmt.Println(format.SuccessMessagef("📝", "set active Project to %s", s.Name)) + return nil }