-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathallow_comments.go
More file actions
65 lines (50 loc) · 2.3 KB
/
Copy pathallow_comments.go
File metadata and controls
65 lines (50 loc) · 2.3 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
package rule
import (
"context"
"entgo.io/ent"
"github.com/samber/lo"
"github.com/theopenlane/core/internal/ent/generated"
"github.com/theopenlane/core/internal/ent/generated/privacy"
"github.com/theopenlane/core/pkg/slateparser"
)
// CheckIfCommentOnly is a rule that returns allow decision if the mutation is a comment-only operation
func CheckIfCommentOnly() privacy.MutationRuleFunc {
return privacy.MutationRuleFunc(func(ctx context.Context, m generated.Mutation) error {
if m.Op().Is(ent.OpCreate) {
return privacy.Skipf("mutation is a create operation, skipping bypass")
}
// get the list of added and removed edges and fields in the mutation
addedEdges := m.AddedEdges()
removedEdges := m.RemovedEdges()
fields := m.Fields()
addedFields := m.AddedFields() // get numeric fields
ignoreFields := []string{"updated_at", "updated_by", "owner_id"}
allowedEdges := []string{"comments", "notes"}
// remove ignored fields from the list of fields being set in the mutation
fields = lo.Without(fields, ignoreFields...)
// remove allowed edges from the list of added and removed edges
addedEdges = lo.Without(addedEdges, allowedEdges...)
removedEdges = lo.Without(removedEdges, allowedEdges...)
if len(addedEdges) == 0 && len(removedEdges) == 0 && len(fields) == 0 && len(addedFields) == 0 {
return privacy.Allowf("mutation has no changes beyond allowed edges, allowing")
}
detailsJSONFieldName := "details_json"
if !lo.Contains(fields, detailsJSONFieldName) {
// try description_json instead
detailsJSONFieldName = "description_json"
}
// if just one fields changed, check the details_json, this is done for plate comments
if len(fields) == 1 && lo.Contains(fields, detailsJSONFieldName) {
// get the old details json value from the mutation
oldDetailsJSON, _ := m.OldField(ctx, detailsJSONFieldName)
newDetailsJSON, _ := m.Field(detailsJSONFieldName)
oldDetailsTyped, _ := oldDetailsJSON.([]any)
newDetailsTyped, _ := newDetailsJSON.([]any)
if slateparser.NoDetailsChanged(oldDetailsTyped, newDetailsTyped) {
return privacy.Allowf("mutation has only comments added to details_json, allowing")
}
}
// if we reach here, changes are beyond scope of comments and we should fall to next rule
return privacy.Skipf("mutation has changes, skipping")
})
}