Skip to content

Commit 038bd8e

Browse files
authored
feat(store): user delete keeps the row (#2023)
1 parent d564023 commit 038bd8e

5 files changed

Lines changed: 126 additions & 4 deletions

File tree

‎internal/store/postgres/org_pats_repository.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,9 +141,9 @@ func (r OrgPATsRepository) Search(ctx context.Context, orgID string, rqlQuery *r
141141
// buildInnerSubquery builds the base PAT query with filters and search applied.
142142
func (r OrgPATsRepository) buildInnerSubquery(orgID string, rqlQuery *rql.Query) (*goqu.SelectDataset, error) {
143143
inner := dialect.From(goqu.T(TABLE_USER_PATS).As("p")).
144-
LeftJoin(
144+
InnerJoin(
145145
goqu.T(TABLE_USERS).As("u"),
146-
goqu.On(goqu.I("p.user_id").Eq(goqu.I("u.id"))),
146+
goqu.On(goqu.I("p.user_id").Eq(goqu.I("u.id")), live("u")),
147147
).
148148
Where(
149149
goqu.I("p.org_id").Eq(orgID),
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package postgres_test
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"testing"
7+
8+
"github.com/raystack/frontier/internal/store/postgres"
9+
"github.com/raystack/frontier/pkg/db"
10+
"github.com/raystack/salt/rql"
11+
"github.com/stretchr/testify/suite"
12+
)
13+
14+
type OrgPATsRepositoryPGTestSuite struct {
15+
suite.Suite
16+
ctx context.Context
17+
client *db.Client
18+
repository *postgres.OrgPATsRepository
19+
orgID string
20+
}
21+
22+
func (s *OrgPATsRepositoryPGTestSuite) SetupSuite() {
23+
var err error
24+
s.client, err = newTestClient()
25+
if err != nil {
26+
s.T().Fatal(err)
27+
}
28+
s.ctx = context.TODO()
29+
s.repository = postgres.NewOrgPATsRepository(s.client)
30+
}
31+
32+
func (s *OrgPATsRepositoryPGTestSuite) TearDownSuite() {
33+
if err := closeTestClient(s.client); err != nil {
34+
s.T().Fatal(err)
35+
}
36+
}
37+
38+
func (s *OrgPATsRepositoryPGTestSuite) SetupTest() {
39+
execSQL(s.T(), s.ctx, s.client, `INSERT INTO organizations (name, title) VALUES ('op-org', 'Org PATs Org')`)
40+
s.orgID = scalarSQL(s.T(), s.ctx, s.client, `SELECT id FROM organizations WHERE name = 'op-org'`)
41+
42+
execSQL(s.T(), s.ctx, s.client, `INSERT INTO users (name, email, title) VALUES
43+
('op-uma', 'op-uma@example.com', 'Uma'),
44+
('op-gary', 'op-gary@example.com', 'Gary')`)
45+
execSQL(s.T(), s.ctx, s.client, `INSERT INTO user_pats (user_id, org_id, title, secret_hash, expires_at) VALUES
46+
((SELECT id FROM users WHERE name = 'op-uma'), $1, 'deploy-token', 'op-hash-uma', now() + interval '1 day'),
47+
((SELECT id FROM users WHERE name = 'op-gary'), $1, 'backup-token', 'op-hash-gary', now() + interval '1 day')`,
48+
s.orgID)
49+
execSQL(s.T(), s.ctx, s.client, `UPDATE users SET deleted_at = now() WHERE name = 'op-gary'`)
50+
}
51+
52+
func (s *OrgPATsRepositoryPGTestSuite) TearDownTest() {
53+
queries := []string{}
54+
for _, table := range []string{postgres.TABLE_USER_PATS, postgres.TABLE_USERS, postgres.TABLE_ORGANIZATIONS} {
55+
queries = append(queries, fmt.Sprintf("TRUNCATE TABLE %s RESTART IDENTITY CASCADE", table))
56+
}
57+
if err := execQueries(s.ctx, s.client, queries); err != nil {
58+
s.T().Fatal(err)
59+
}
60+
}
61+
62+
func (s *OrgPATsRepositoryPGTestSuite) search(text string) ([]string, int64) {
63+
s.T().Helper()
64+
res, err := s.repository.Search(s.ctx, s.orgID, &rql.Query{Limit: 50, Search: text})
65+
s.Require().NoError(err)
66+
titles := make([]string, 0, len(res.PATs))
67+
for _, pat := range res.PATs {
68+
titles = append(titles, pat.Title)
69+
}
70+
return titles, res.Pagination.TotalCount
71+
}
72+
73+
func (s *OrgPATsRepositoryPGTestSuite) TestSkipsPATsOfSoftDeletedUsers() {
74+
titles, total := s.search("")
75+
s.Equal([]string{"deploy-token"}, titles)
76+
s.Equal(int64(1), total)
77+
}
78+
79+
func (s *OrgPATsRepositoryPGTestSuite) TestSearchMatchesLiveOwnersOnly() {
80+
titles, _ := s.search("Uma")
81+
s.Equal([]string{"deploy-token"}, titles)
82+
83+
titles, total := s.search("Gary")
84+
s.Empty(titles, "the owner is soft-deleted")
85+
s.Zero(total)
86+
}
87+
88+
func TestOrgPATsRepositoryPG(t *testing.T) {
89+
suite.Run(t, new(OrgPATsRepositoryPGTestSuite))
90+
}

‎internal/store/postgres/org_pats_repository_test.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import (
1212
"github.com/stretchr/testify/assert"
1313
)
1414

15+
const liveOwnerJoin = `INNER JOIN "users" AS "u" ON (("p"."user_id" = "u"."id") AND ("u"."deleted_at" IS NULL))`
16+
1517
func TestOrgPATsRepository_buildCountQuery(t *testing.T) {
1618
r := OrgPATsRepository{}
1719

@@ -66,6 +68,7 @@ func TestOrgPATsRepository_buildCountQuery(t *testing.T) {
6668
assert.NoError(t, err)
6769
assert.NotEmpty(t, sql)
6870
assert.Contains(t, sql, "COUNT(*)")
71+
assert.Contains(t, sql, liveOwnerJoin)
6972
assert.NotContains(t, sql, "ORDER BY")
7073
assert.NotEmpty(t, params)
7174
})
@@ -135,6 +138,7 @@ func TestOrgPATsRepository_buildDataQuery(t *testing.T) {
135138
assert.Contains(t, sql, "pat_id")
136139
assert.Contains(t, sql, "created_by_title")
137140
assert.Contains(t, sql, "pol")
141+
assert.Contains(t, sql, liveOwnerJoin)
138142
assert.NotEmpty(t, params)
139143

140144
// the live filter sits in the policies join, not in a WHERE clause

‎internal/store/postgres/user_repository.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,7 @@ func (r UserRepository) SetState(ctx context.Context, id string, state user.Stat
556556
}
557557

558558
func (r UserRepository) Delete(ctx context.Context, id string) error {
559-
query, params, err := dialect.Delete(TABLE_USERS).Where(
559+
query, params, err := softDelete(TABLE_USERS).Where(
560560
goqu.Ex{
561561
"id": id,
562562
},
@@ -572,7 +572,7 @@ func (r UserRepository) Delete(ctx context.Context, id string) error {
572572
}); err != nil {
573573
return err
574574
}
575-
return InsertAuditRecordInTx(ctx, tx, buildUserAuditRecord(ctx, auditrecord.UserDeletedEvent, userModel, time.Now().UTC()))
575+
return InsertAuditRecordInTx(ctx, tx, buildUserAuditRecord(ctx, auditrecord.UserDeletedEvent, userModel, userModel.DeletedAt.Time))
576576
}); err != nil {
577577
err = checkPostgresError(err)
578578
switch {

‎internal/store/postgres/user_repository_test.go‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ package postgres_test
22

33
import (
44
"context"
5+
"database/sql"
56
"errors"
67
"fmt"
78
"testing"
9+
"time"
810

911
"github.com/google/go-cmp/cmp"
1012
"github.com/google/go-cmp/cmp/cmpopts"
@@ -506,6 +508,32 @@ func (s *UserRepositoryTestSuite) TestDelete() {
506508
}
507509
}
508510

511+
func (s *UserRepositoryTestSuite) TestDeleteKeepsTheRow() {
512+
deleted := s.users[0]
513+
514+
s.Require().NoError(s.repository.Delete(s.ctx, deleted.ID))
515+
516+
var deletedAt sql.NullTime
517+
s.Require().NoError(s.client.GetContext(s.ctx, &deletedAt, "SELECT deleted_at FROM users WHERE id = $1", deleted.ID))
518+
s.Require().True(deletedAt.Valid)
519+
520+
var occurredAt time.Time
521+
s.Require().NoError(s.client.GetContext(s.ctx, &occurredAt,
522+
"SELECT occurred_at FROM audit_records WHERE event = $1 AND target_id = $2",
523+
pkgAuditRecord.UserDeletedEvent.String(), deleted.ID))
524+
s.Assert().WithinDuration(deletedAt.Time, occurredAt, 0)
525+
526+
_, err := s.repository.GetByID(s.ctx, deleted.ID)
527+
s.Assert().ErrorIs(err, user.ErrNotExist)
528+
529+
s.Assert().ErrorIs(s.repository.Delete(s.ctx, deleted.ID), user.ErrNotExist)
530+
s.assertAudited(pkgAuditRecord.UserDeletedEvent.String(), deleted.ID, uuid.Nil.String())
531+
532+
again, err := s.repository.Create(s.ctx, user.User{Name: deleted.Name, Email: deleted.Email})
533+
s.Require().NoError(err)
534+
s.Assert().NotEqual(deleted.ID, again.ID)
535+
}
536+
509537
func (s *UserRepositoryTestSuite) TestSetState() {
510538
type testCase struct {
511539
Description string

0 commit comments

Comments
 (0)