refactor(postgres): split lifecycle exit side effects out of Apply

This commit is contained in:
sam committed 2026-10-17 10:10:02 +11:00
1 parent 42ba637935
commit 9b7e7fc221
1 file changed
+17 -9
+17 -9
View File
@@ -174,10 +174,8 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi
now = time.Now().UTC()
}
next.UpdatedAt = now
if cur.Lifecycle == identity.LifecycleActive && next.Lifecycle != identity.LifecycleActive {
if err := keepActiveOwner(ctx, tx, string(id), ""); err != nil {
return identity.Identity{}, err
}
if err := guardLeavingActive(ctx, tx, id, cur.Lifecycle, next.Lifecycle); err != nil {
return identity.Identity{}, err
}
n, err := q.UpdateIdentity(ctx, postgresdb.UpdateIdentityParams{
@@ -190,11 +188,6 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi
if n != 1 {
return identity.Identity{}, identity.ErrConflict
}
if next.Lifecycle != identity.LifecycleActive {
if _, err := tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, string(id)); err != nil {
return identity.Identity{}, err
}
}
if command.Type == identity.CommandRename {
if err := q.InsertIdentityAliasIgnoreConflict(ctx, postgresdb.InsertIdentityAliasIgnoreConflictParams{
Alias: next.DisplayName, IdentityID: string(id),
@@ -211,6 +204,21 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi
return next, nil
}
// guardLeavingActive refuses suspending or retiring an org's last active
// owner, and signs out an identity that may no longer act.
func guardLeavingActive(ctx context.Context, tx pgx.Tx, id identity.IdentityID, from, to identity.Lifecycle) error {
if to == identity.LifecycleActive {
return nil
}
if from == identity.LifecycleActive {
if err := keepActiveOwner(ctx, tx, string(id), ""); err != nil {
return err
}
}
_, err := tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, string(id))
return err
}
// ResolveSubject returns the identity bound to a provider subject.
func (s *Store) ResolveSubject(ctx context.Context, subject identity.Subject) (identity.Identity, error) {
i, err := s.queries().ResolveIdentitySubject(ctx, postgresdb.ResolveIdentitySubjectParams{