@@ -114,7 +114,9 @@ func (r *PostgresUserReconciler) Reconcile(ctx context.Context, req ctrl.Request
114114 }
115115
116116 // Creation logic
117- var role , login string
117+ var (
118+ role , login string
119+ )
118120 password , err := utils .GetSecureRandomString (15 )
119121
120122 if err != nil {
@@ -171,6 +173,59 @@ func (r *PostgresUserReconciler) Reconcile(ctx context.Context, req ctrl.Request
171173 login = instance .Status .PostgresLogin
172174 }
173175
176+ // Reconcile logic for changes in group membership
177+ // This is only applicable if user role is already created
178+ // and privileges are changed in spec
179+ if instance .Status .PostgresRole != "" {
180+
181+ // We need to get the Postgres CR to get the group role name
182+ database , err := r .getPostgresCR (ctx , instance )
183+ if err != nil {
184+ return r .requeue (ctx , instance , errors .NewInternalError (err ))
185+ }
186+
187+ // Determine desired group role
188+ var desiredGroup string
189+ switch instance .Spec .Privileges {
190+ case "READ" :
191+ desiredGroup = database .Status .Roles .Reader
192+ case "WRITE" :
193+ desiredGroup = database .Status .Roles .Writer
194+ default :
195+ desiredGroup = database .Status .Roles .Owner
196+ }
197+
198+ currentGroup := instance .Status .PostgresGroup
199+ if desiredGroup != "" && currentGroup != desiredGroup {
200+
201+ // Remove the old group membership if present
202+ if currentGroup != "" {
203+ err = r .pg .RevokeRole (currentGroup , role )
204+ if err != nil {
205+ return r .requeue (ctx , instance , errors .NewInternalError (err ))
206+ }
207+ }
208+
209+ // Grant the new group role
210+ err = r .pg .GrantRole (desiredGroup , role )
211+ if err != nil {
212+ return r .requeue (ctx , instance , errors .NewInternalError (err ))
213+ }
214+
215+ // Ensure objects created by the user are owned by the new group
216+ err = r .pg .AlterDefaultLoginRole (role , desiredGroup )
217+ if err != nil {
218+ return r .requeue (ctx , instance , errors .NewInternalError (err ))
219+ }
220+
221+ instance .Status .PostgresGroup = desiredGroup
222+ err = r .Status ().Update (ctx , instance )
223+ if err != nil {
224+ return r .requeue (ctx , instance , err )
225+ }
226+ }
227+ }
228+
174229 err = r .addFinalizer (ctx , reqLogger , instance )
175230 if err != nil {
176231 return r .requeue (ctx , instance , err )
0 commit comments