-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathtrustcenterndarequest.go
More file actions
382 lines (311 loc) · 11.9 KB
/
Copy pathtrustcenterndarequest.go
File metadata and controls
382 lines (311 loc) · 11.9 KB
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package hooks
import (
"context"
"fmt"
"time"
"entgo.io/ent"
"github.com/samber/lo"
"github.com/theopenlane/iam/auth"
"github.com/theopenlane/iam/fgax"
"github.com/theopenlane/core/common/enums"
"github.com/theopenlane/core/common/models"
"github.com/theopenlane/core/internal/ent/generated"
"github.com/theopenlane/core/internal/ent/generated/hook"
"github.com/theopenlane/core/internal/ent/generated/organization"
"github.com/theopenlane/core/internal/ent/generated/orgmembership"
"github.com/theopenlane/core/internal/ent/generated/privacy"
"github.com/theopenlane/core/internal/ent/generated/template"
"github.com/theopenlane/core/internal/ent/generated/trustcenter"
"github.com/theopenlane/core/internal/ent/generated/trustcenterndarequest"
"github.com/theopenlane/core/internal/httpserve/authmanager"
emaildef "github.com/theopenlane/core/internal/integrations/definitions/email"
"github.com/theopenlane/core/pkg/logx"
)
// HookTrustCenterNDARequestCreate handles new NDA request creation
func HookTrustCenterNDARequestCreate() ent.Hook {
return hook.On(func(next ent.Mutator) ent.Mutator {
return hook.TrustCenterNDARequestFunc(func(ctx context.Context, m *generated.TrustCenterNDARequestMutation) (generated.Value, error) {
trustCenterID, ok := m.TrustCenterID()
if !ok || trustCenterID == "" {
logx.FromContext(ctx).Error().Msg("trust center ID is required for NDA request")
return nil, ErrTrustCenterIDRequired
}
n, err := m.Client().Template.Query().
Select(template.FieldID).
Where(template.KindEQ(enums.TemplateKindTrustCenterNda)).
Count(ctx)
if err != nil {
return nil, err
}
if n == 0 {
return nil, ErrNDATemplateRequired
}
email, _ := m.Email()
queryCtx := ctx
if _, isAnon := auth.ActiveTrustCenterIDKey.Get(ctx); isAnon {
queryCtx = privacy.DecisionContext(ctx, privacy.Allow)
}
existingRequest, err := m.Client().TrustCenterNDARequest.Query().
Where(
trustcenterndarequest.TrustCenterIDEQ(trustCenterID),
trustcenterndarequest.EmailEQ(email),
).
Only(queryCtx)
if err != nil && !generated.IsNotFound(err) {
return nil, err
}
if existingRequest != nil {
return handleExistingNDARequest(ctx, queryCtx, m.Client(), existingRequest)
}
tc, err := m.Client().TrustCenter.Query().
Where(trustcenter.IDEQ(trustCenterID)).
WithSetting().
Only(queryCtx)
if err != nil {
return nil, err
}
requiresApproval := tc.Edges.Setting != nil && tc.Edges.Setting.NdaApprovalRequired
if requiresApproval {
m.SetStatus(enums.TrustCenterNDARequestStatusNeedsApproval)
}
v, err := next.Mutate(ctx, m)
if err != nil {
return nil, err
}
request, ok := v.(*generated.TrustCenterNDARequest)
if !ok {
return v, nil
}
if requiresApproval {
if err := createNDARequestNotification(ctx, request, tc.OwnerID); err != nil {
logx.FromContext(ctx).Error().Err(err).Msg("failed to create NDA request notification")
}
if err := sendNDAApprovalRequestEmails(ctx, m.Client(), request, tc.OwnerID); err != nil {
logx.FromContext(ctx).Error().Err(err).Msg("failed to send NDA approval request emails")
}
return v, nil
}
if err := sendSystemEmail(ctx, m.Client(), emaildef.TCNDARequestOp.Name(), emaildef.TrustCenterNDARequestEmail{
RecipientInfo: emaildef.RecipientInfo{Email: request.Email},
RequestID: request.ID,
TrustCenterID: request.TrustCenterID,
}); err != nil {
return nil, err
}
return v, nil
})
}, ent.OpCreate)
}
func handleExistingNDARequest(ctx, queryCtx context.Context, client *generated.Client, existing *generated.TrustCenterNDARequest) (*generated.TrustCenterNDARequest, error) {
switch existing.Status {
case enums.TrustCenterNDARequestStatusSigned:
if err := sendSystemEmail(ctx, client, emaildef.TCAuthOp.Name(), emaildef.TrustCenterAuthEmail{
RecipientInfo: emaildef.RecipientInfo{Email: existing.Email},
RequestID: existing.ID,
TrustCenterID: existing.TrustCenterID,
}); err != nil {
return nil, err
}
return existing, nil
case enums.TrustCenterNDARequestStatusApproved, enums.TrustCenterNDARequestStatusRequested:
if err := sendSystemEmail(ctx, client, emaildef.TCNDARequestOp.Name(), emaildef.TrustCenterNDARequestEmail{
RecipientInfo: emaildef.RecipientInfo{Email: existing.Email},
RequestID: existing.ID,
TrustCenterID: existing.TrustCenterID,
}); err != nil {
return nil, err
}
return existing, nil
case enums.TrustCenterNDARequestStatusNeedsApproval:
// if needs approval, recreate notification
tc, err := getTrustCenter(ctx, existing.TrustCenterID)
if err != nil {
return nil, err
}
if err := createNDARequestNotification(ctx, existing, tc.OwnerID); err != nil {
logx.FromContext(ctx).Error().Err(err).Msg("failed to create NDA request notification")
}
if err := sendNDAApprovalRequestEmails(ctx, client, existing, tc.OwnerID); err != nil {
logx.FromContext(ctx).Error().Err(err).Msg("failed to send NDA approval request emails")
}
return existing, nil
case enums.TrustCenterNDARequestStatusDeclined:
// if previously declined, set to needs approval again to restart the process
if err := transactionFromContext(ctx).TrustCenterNDARequest.UpdateOne(existing).SetStatus(enums.TrustCenterNDARequestStatusNeedsApproval).
Exec(queryCtx); err != nil {
logx.FromContext(ctx).Error().Err(err).Str("email", existing.Email).Msg("failed to update NDA request status to needs approval")
return nil, err
}
tc, err := getTrustCenter(ctx, existing.TrustCenterID)
if err != nil {
return nil, err
}
if err := createNDARequestNotification(ctx, existing, tc.OwnerID); err != nil {
logx.FromContext(ctx).Error().Err(err).Msg("failed to create NDA request notification")
}
if err := sendNDAApprovalRequestEmails(ctx, client, existing, tc.OwnerID); err != nil {
logx.FromContext(ctx).Error().Err(err).Msg("failed to send NDA approval request emails")
}
}
// otherwise do nothing invalid
return existing, nil
}
// getTrustCenter is a helper to get the trust center for an NDA request by ID
func getTrustCenter(ctx context.Context, trustCenterID string) (*generated.TrustCenter, error) {
tc, err := transactionFromContext(ctx).TrustCenter.Query().
Where(trustcenter.IDEQ(trustCenterID)).
Only(ctx)
if err != nil {
logx.FromContext(ctx).Error().Err(err).Str("trust_center_id", trustCenterID).Msg("failed to get trust center for existing NDA request")
return nil, err
}
return tc, nil
}
// HookTrustCenterNDARequestUpdate handles NDA request status updates - sends email when approved
func HookTrustCenterNDARequestUpdate() ent.Hook {
return hook.On(func(next ent.Mutator) ent.Mutator {
return hook.TrustCenterNDARequestFunc(func(ctx context.Context, m *generated.TrustCenterNDARequestMutation) (generated.Value, error) {
if isDeleteOp(ctx, m) {
if err := handleNDARequestDelete(ctx, m); err != nil {
return nil, err
}
return next.Mutate(ctx, m)
}
status, ok := m.Status()
// on update one, check if status is set, if not get old status
if m.Op().Is(ent.OpUpdateOne) && (!ok || status == "") {
oldStatus, err := m.OldStatus(ctx)
// if status isn't set on mutation, set to the old status
if err == nil && status == "" {
status = oldStatus
}
}
if !ok || (status != enums.TrustCenterNDARequestStatusApproved && status != enums.TrustCenterNDARequestStatusSigned) {
return next.Mutate(ctx, m)
}
// if approved or signed, set the timestamp in the ISO8601 format
now, err := models.ToDateTime(time.Now().UTC().Format(time.RFC3339))
if err != nil {
return nil, err
}
if status == enums.TrustCenterNDARequestStatusSigned {
m.SetSignedAt(*now)
retVal, err := next.Mutate(ctx, m)
if err != nil {
return nil, err
}
return retVal, nil
}
m.SetApprovedAt(*now)
v, err := next.Mutate(ctx, m)
if err != nil {
return nil, err
}
request, ok := v.(*generated.TrustCenterNDARequest)
if !ok {
return v, nil
}
if err := sendSystemEmail(ctx, m.Client(), emaildef.TCNDARequestOp.Name(), emaildef.TrustCenterNDARequestEmail{
RecipientInfo: emaildef.RecipientInfo{Email: request.Email},
RequestID: request.ID,
TrustCenterID: request.TrustCenterID,
}); err != nil {
return nil, err
}
return v, nil
})
}, ent.OpUpdateOne|ent.OpUpdate|ent.OpDeleteOne)
}
func handleNDARequestDelete(ctx context.Context, m *generated.TrustCenterNDARequestMutation) error {
id, ok := m.ID()
if !ok {
logx.FromContext(ctx).Error().Msg("missing ID for deleted NDA request, unable to cleanup tuples")
return nil
}
tcID, ok := m.TrustCenterID()
if !ok && m.Op().Is(ent.OpUpdateOne) {
oldTrustcenterID, err := m.OldTrustCenterID(ctx)
if err != nil {
logx.FromContext(ctx).Error().Err(err).Msg("missing trust center ID for deleted NDA request, unable to cleanup tuples")
return err
}
tcID = oldTrustcenterID
}
// delete any tuples associated with the nda request
deleteTuple := fgax.GetTupleKey(fgax.TupleRequest{
SubjectID: fmt.Sprintf("%s%s", authmanager.AnonTrustCenterJWTPrefix, id),
SubjectType: "user",
ObjectID: tcID,
ObjectType: "trust_center",
Relation: "nda_signed",
})
if _, err := m.Authz.WriteTupleKeys(ctx, nil, []fgax.TupleKey{deleteTuple}); err != nil {
logx.FromContext(ctx).Error().Err(err).Msg("failed to delete relationship tuple for deleted NDA request")
return ErrInternalServerError
}
return nil
}
func createNDARequestNotification(ctx context.Context, ndaRequest *generated.TrustCenterNDARequest, ownerID string) error {
name := fmt.Sprintf("%s %s", ndaRequest.FirstName, ndaRequest.LastName)
if name == " " {
name = ndaRequest.Email
}
topic := enums.NotificationTopicApproval
input := generated.CreateNotificationInput{
NotificationType: enums.NotificationTypeOrganization,
Title: "New NDA Access Request",
Body: fmt.Sprintf("%s has requested access to private trust center documents.", name),
ObjectType: "trust_center_nda_request",
OwnerID: &ownerID,
Topic: &topic,
Data: map[string]any{
"nda_request_id": ndaRequest.ID,
"trust_center_id": ndaRequest.TrustCenterID,
"email": ndaRequest.Email,
"url": "trust-center/NDAs",
},
}
allowCtx := privacy.DecisionContext(ctx, privacy.Allow)
_, err := transactionFromContext(ctx).Notification.Create().SetInput(input).Save(allowCtx)
return err
}
// ndaApproverRoles are the organization roles permitted to review and approve trust center NDA requests
var ndaApproverRoles = []enums.Role{enums.RoleOwner, enums.RoleSuperAdmin, enums.RoleAdmin}
// sendNDAApprovalRequestEmails notifies the organization's owners and admins, in a single message,
// that a trust center NDA request is pending their approval
func sendNDAApprovalRequestEmails(ctx context.Context, client *generated.Client, ndaRequest *generated.TrustCenterNDARequest, ownerID string) error {
allowCtx := privacy.DecisionContext(ctx, privacy.Allow)
org, err := client.Organization.Query().
Where(organization.IDEQ(ownerID)).
Select(organization.FieldDisplayName).
Only(allowCtx)
if err != nil {
return err
}
approvers, err := client.OrgMembership.Query().
Where(
orgmembership.OrganizationID(ownerID),
orgmembership.RoleIn(ndaApproverRoles...),
).
WithUser().
All(allowCtx)
if err != nil {
return err
}
emails := lo.Map(approvers, func(approver *generated.OrgMembership, _ int) string {
return approver.Edges.User.Email
})
if len(emails) == 0 {
return nil
}
requesterName := fmt.Sprintf("%s %s", ndaRequest.FirstName, ndaRequest.LastName)
if requesterName == " " {
requesterName = ""
}
return sendSystemEmail(ctx, client, emaildef.TCNDAApprovalRequestOp.Name(), emaildef.TrustCenterNDAApprovalRequestEmail{
RecipientInfo: emaildef.RecipientInfo{Email: emails[0], Recipients: emails},
OrgName: org.DisplayName,
RequesterName: requesterName,
RequesterEmail: ndaRequest.Email,
})
}