generated from datumforge/go-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
allow_if_self.go
50 lines (41 loc) · 1.28 KB
/
allow_if_self.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
package rule
import (
"context"
"entgo.io/ent/entql"
"github.com/datumforge/entx"
"github.com/datumforge/datum/internal/ent/generated/privacy"
"github.com/datumforge/datum/pkg/auth"
)
// AllowIfSelf determines whether a query or mutation operation should be allowed based on whether the requested data is for the viewer
func AllowIfSelf() privacy.QueryMutationRule {
return privacy.FilterFunc(func(ctx context.Context, f privacy.Filter) error {
// IDFilter is used for the user table
type IDFilter interface {
WhereID(entql.StringP)
}
// UserIDFilter is used for the user_setting table
type UserIDFilter interface {
WhereUserID(entql.StringP)
}
// if the user setting is being deleted, allow it
// there are no resolvers, this will always be deleted as part
// of a cascade delete
if _, ok := f.(UserIDFilter); ok && entx.CheckIsSoftDelete(ctx) {
return privacy.Allow
}
userID, err := auth.GetUserIDFromContext(ctx)
if err != nil {
return privacy.Skipf("anonymous viewer")
}
switch actualFilter := f.(type) {
case UserIDFilter:
actualFilter.WhereUserID(entql.StringEQ(userID))
case IDFilter:
actualFilter.WhereID(entql.StringEQ(userID))
default:
return privacy.Denyf("unexpected filter type %T", f)
}
return privacy.Allow
},
)
}