Add grants to project

[ZITADOPER-1]
This commit is contained in:
Haim Kortovich
2024-05-17 13:51:08 -05:00
parent 822a2a22ef
commit 626e33a773
5 changed files with 190 additions and 0 deletions

View File

@@ -19,6 +19,8 @@ package controller
import (
"context"
"fmt"
"reflect"
"sort"
"strings"
"time"
@@ -28,6 +30,7 @@ import (
"github.com/zitadel/zitadel-go/v2/pkg/client/management"
"github.com/zitadel/zitadel-go/v2/pkg/client/middleware"
pb "github.com/zitadel/zitadel-go/v2/pkg/client/zitadel/management"
"github.com/zitadel/zitadel-go/v2/pkg/client/zitadel/project"
"golang.org/x/exp/maps"
"k8s.io/client-go/util/workqueue"
ctrl "sigs.k8s.io/controller-runtime"
@@ -107,6 +110,10 @@ func (wr *wrappedProjectReconciler) Reconcile(ctx context.Context, ztdClient *ma
Name: "roles",
Reconcile: wr.reconcileRoles,
},
{
Name: "grants",
Reconcile: wr.reconcileGrants,
},
}
for _, p := range phases {
err := p.Reconcile(ctx, ztdClient)
@@ -219,6 +226,57 @@ func (wr *wrappedProjectReconciler) reconcileRoles(ctx context.Context, ztdClien
return nil
}
func (wr *wrappedProjectReconciler) reconcileGrants(ctx context.Context, ztdClient *management.Client) error {
org, err := wr.refResolver.OrganizationRef(ctx, &wr.project.Spec.OrganizationRef, wr.project.Namespace)
if err != nil {
return err
}
existingGrants, err := ztdClient.ListProjectGrants(ctx, &pb.ListProjectGrantsRequest{
ProjectId: wr.project.Status.ProjectId,
})
if err != nil {
return fmt.Errorf("Error listing project grants: %v", err)
}
ctx = middleware.SetOrgID(ctx, org.Status.OrgId)
for _, grant := range wr.project.DeepCopy().Spec.Grants {
grantedOrg, err := wr.refResolver.OrganizationRef(ctx, &grant.OrganizationRef, wr.project.Namespace)
if err != nil {
return err
}
var existingGrant *project.GrantedProject
for _, eGrant := range existingGrants.Result {
if eGrant.GrantedOrgId == grantedOrg.Status.OrgId {
existingGrant = eGrant
break
}
}
if existingGrant == nil {
_, err := ztdClient.AddProjectGrant(ctx, &pb.AddProjectGrantRequest{
ProjectId: wr.project.Status.ProjectId,
GrantedOrgId: grantedOrg.Status.OrgId,
RoleKeys: grant.RoleKeys,
})
if err != nil {
return fmt.Errorf("Error Adding project grant: %v", err)
}
} else {
sort.Strings(existingGrant.GrantedRoleKeys)
sort.Strings(grant.RoleKeys)
if !reflect.DeepEqual(existingGrant.GrantedRoleKeys, grant.RoleKeys) {
_, err := ztdClient.UpdateProjectGrant(ctx, &pb.UpdateProjectGrantRequest{
ProjectId: wr.project.Status.ProjectId,
GrantId: existingGrant.GrantId,
RoleKeys: grant.RoleKeys,
})
if err != nil {
return fmt.Errorf("Error Updating project grant: %v", err)
}
}
}
}
return nil
}
func (wr *wrappedProjectReconciler) PatchStatus(ctx context.Context, patcher condition.Patcher) error {
patch := client.MergeFrom(wr.project.DeepCopy())
patcher(&wr.project.Status)