/
grant_repository.go
239 lines (210 loc) · 5.99 KB
/
grant_repository.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package postgres
import (
"context"
"errors"
"fmt"
"github.com/lib/pq"
"github.com/raystack/guardian/core/grant"
"github.com/raystack/guardian/domain"
"github.com/raystack/guardian/internal/store/postgres/model"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
var (
GrantStatusDefaultSort = []string{
string(domain.GrantStatusActive),
string(domain.GrantStatusInactive),
}
)
type GrantRepository struct {
db *gorm.DB
}
func NewGrantRepository(db *gorm.DB) *GrantRepository {
return &GrantRepository{db}
}
func (r *GrantRepository) List(ctx context.Context, filter domain.ListGrantsFilter) ([]domain.Grant, error) {
db := r.db.WithContext(ctx)
if filter.AccountIDs != nil {
db = db.Where(`"grants"."account_id" IN ?`, filter.AccountIDs)
}
if filter.AccountTypes != nil {
db = db.Where(`"grants"."account_type" IN ?`, filter.AccountTypes)
}
if filter.ResourceIDs != nil {
db = db.Where(`"grants"."resource_id" IN ?`, filter.ResourceIDs)
}
if filter.Statuses != nil {
db = db.Where(`"grants"."status" IN ?`, filter.Statuses)
}
if filter.Roles != nil {
db = db.Where(`"grants"."role" IN ?`, filter.Roles)
}
if filter.Permissions != nil {
db = db.Where(`"grants"."permissions" @> ?`, pq.StringArray(filter.Permissions))
}
if filter.Owner != "" {
db = db.Where(`"grants"."owner" = ?`, filter.Owner)
} else if filter.CreatedBy != "" {
db = db.Where(`"grants"."owner" = ?`, filter.CreatedBy)
}
if filter.IsPermanent != nil {
db = db.Where(`"grants"."is_permanent" = ?`, *filter.IsPermanent)
}
if filter.OrderBy != nil {
db = addOrderByClause(db, filter.OrderBy, addOrderByClauseOptions{
statusColumnName: `"grants"."status"`,
statusesOrder: GrantStatusDefaultSort,
})
}
if !filter.ExpirationDateLessThan.IsZero() {
db = db.Where(`"grants"."expiration_date" < ?`, filter.ExpirationDateLessThan)
}
if !filter.ExpirationDateGreaterThan.IsZero() {
db = db.Where(`"grants"."expiration_date" > ?`, filter.ExpirationDateGreaterThan)
}
if filter.ProviderTypes != nil {
db = db.Where(`"Resource"."provider_type" IN ?`, filter.ProviderTypes)
}
if filter.ProviderURNs != nil {
db = db.Where(`"Resource"."provider_urn" IN ?`, filter.ProviderURNs)
}
if filter.ResourceTypes != nil {
db = db.Where(`"Resource"."type" IN ?`, filter.ResourceTypes)
}
if filter.ResourceURNs != nil {
db = db.Where(`"Resource"."urn" IN ?`, filter.ResourceURNs)
}
var models []model.Grant
if err := db.Joins("Resource").Joins("Appeal").Find(&models).Error; err != nil {
return nil, err
}
var grants []domain.Grant
for _, m := range models {
g, err := m.ToDomain()
if err != nil {
return nil, fmt.Errorf("parsing grant %q: %w", g.ID, err)
}
grants = append(grants, *g)
}
return grants, nil
}
func (r *GrantRepository) GetByID(ctx context.Context, id string) (*domain.Grant, error) {
m := new(model.Grant)
if err := r.db.WithContext(ctx).Joins("Resource").Joins("Appeal").First(&m, `"grants"."id" = ?`, id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, grant.ErrGrantNotFound
}
return nil, err
}
g, err := m.ToDomain()
if err != nil {
return nil, fmt.Errorf("parsing grant %q: %w", g.ID, err)
}
return g, nil
}
func (r *GrantRepository) Update(ctx context.Context, a *domain.Grant) error {
if a == nil || a.ID == "" {
return grant.ErrEmptyIDParam
}
m := new(model.Grant)
if err := m.FromDomain(*a); err != nil {
return fmt.Errorf("parsing grant payload: %w", err)
}
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Model(m).Updates(*m).Error; err != nil {
return err
}
newGrant, err := m.ToDomain()
if err != nil {
return fmt.Errorf("parsing grant: %w", err)
}
*a = *newGrant
return nil
})
}
func (r *GrantRepository) BulkInsert(ctx context.Context, grants []*domain.Grant) error {
var models []*model.Grant
for _, g := range grants {
m := new(model.Grant)
if err := m.FromDomain(*g); err != nil {
return fmt.Errorf("serializing grant: %w", err)
}
models = append(models, m)
}
if len(models) > 0 {
return r.db.Transaction(func(tx *gorm.DB) error {
if err := r.db.Create(models).Error; err != nil {
return err
}
for i, m := range models {
newGrant, err := m.ToDomain()
if err != nil {
return fmt.Errorf("deserializing grant %q: %w", newGrant.ID, err)
}
*grants[i] = *newGrant
}
return nil
})
}
return nil
}
func (r *GrantRepository) BulkUpsert(ctx context.Context, grants []*domain.Grant) error {
models := []*model.Grant{}
for _, g := range grants {
m := new(model.Grant)
if err := m.FromDomain(*g); err != nil {
return fmt.Errorf("serializing grant: %w", err)
}
models = append(models, m)
}
return r.db.Transaction(func(tx *gorm.DB) error {
// upsert resources separately to avoid resource upsertion duplicate issue
if err := upsertResources(tx, models); err != nil {
return fmt.Errorf("upserting resources: %w", err)
}
tx = tx.Omit("Resource")
if err := tx.
Clauses(clause.OnConflict{UpdateAll: true}).
Create(models).
Error; err != nil {
return err
}
for i, m := range models {
newGrant, err := m.ToDomain()
if err != nil {
return fmt.Errorf("deserializing grant %q: %w", newGrant.ID, err)
}
*grants[i] = *newGrant
}
return nil
})
}
func upsertResources(tx *gorm.DB, models []*model.Grant) error {
uniqueResourcesMap := map[string]*model.Resource{}
for _, m := range models {
if r := m.Resource; r != nil {
key := getResourceUniqueURN(*r)
if _, exists := uniqueResourcesMap[key]; !exists {
uniqueResourcesMap[key] = r
} else {
m.Resource = uniqueResourcesMap[key]
}
}
}
var resources []*model.Resource
for _, r := range uniqueResourcesMap {
resources = append(resources, r)
}
if len(resources) > 0 {
if err := tx.Create(resources).Error; err != nil {
return fmt.Errorf("failed to upsert resources: %w", err)
}
}
for _, g := range models {
// set resource id after upsertion
if g.Resource != nil {
g.ResourceID = g.Resource.ID.String()
}
}
return nil
}