Skip to content

Commit

Permalink
Create user if they do not exist
Browse files Browse the repository at this point in the history
  • Loading branch information
HappyTetrahedron committed Feb 9, 2024
1 parent f4cf410 commit cdbf993
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
16 changes: 15 additions & 1 deletion controllers/default_organization_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"context"

"go.uber.org/multierr"
apierrors "k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
Expand Down Expand Up @@ -68,7 +70,19 @@ func (r *DefaultOrganizationReconciler) Reconcile(ctx context.Context, req ctrl.
func setUserDefaultOrganization(ctx context.Context, c client.Client, userName string, orgName string) error {
user := controlv1.User{}
if err := c.Get(ctx, types.NamespacedName{Name: userName}, &user); err != nil {
return err
if !apierrors.IsNotFound(err) {
return err
}
return c.Create(ctx, &controlv1.User{
ObjectMeta: v1.ObjectMeta{
Name: userName,
},
Spec: controlv1.UserSpec{
Preferences: controlv1.UserPreferences{
DefaultOrganizationRef: orgName,
},
},
})
}

if user.Spec.Preferences.DefaultOrganizationRef != "" {
Expand Down
29 changes: 29 additions & 0 deletions controllers/default_organization_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,35 @@ func Test_DefaultOrganizationReconciler_Reconcile_NoMembership_Sucess(t *testing

}

func Test_DefaultOrganizationReconciler_Reconcile_UserNotExist_Sucess(t *testing.T) {
ctx := context.Background()
c := prepareTest(t, &testMemberships1, &u1)
fakeRecorder := record.NewFakeRecorder(3)

_, err := (&DefaultOrganizationReconciler{
Client: c,
Scheme: c.Scheme(),
Recorder: fakeRecorder,
}).Reconcile(ctx, ctrl.Request{
NamespacedName: types.NamespacedName{
Name: testMemberships1.Name,
Namespace: testMemberships1.Namespace,
},
})
require.NoError(t, err)

user := controlv1.User{}
require.NoError(t, c.Get(context.TODO(), types.NamespacedName{Name: u1.ObjectMeta.Name}, &user))
assert.Equal(t, testMemberships1.ObjectMeta.Namespace, user.Spec.Preferences.DefaultOrganizationRef)

require.NoError(t, c.Get(context.TODO(), types.NamespacedName{Name: u2.ObjectMeta.Name}, &user))
assert.Equal(t, testMemberships1.ObjectMeta.Namespace, user.Spec.Preferences.DefaultOrganizationRef)

require.NoError(t, c.Get(context.TODO(), types.NamespacedName{Name: u3.ObjectMeta.Name}, &user))
assert.Equal(t, testMemberships1.ObjectMeta.Namespace, user.Spec.Preferences.DefaultOrganizationRef)

}

func Test_DefaultOrganizationReconciler_Reconcile_Error(t *testing.T) {
failU4 := controlv1.User{
ObjectMeta: metav1.ObjectMeta{
Expand Down

0 comments on commit cdbf993

Please sign in to comment.