llzai/axonhub
0
1package scopes
2
3import (
4 "context"
5
6 "github.com/looplj/axonhub/internal/contexts"
7 "github.com/looplj/axonhub/internal/ent"
8 "github.com/looplj/axonhub/internal/ent/privacy"
9)
10
11// UserReadScopeRule checks read permissions.
12func UserReadScopeRule(readScope ScopeSlug) privacy.QueryRule {
13 return userScopeQueryRule{requiredScope: readScope}
14}
15
16// userScopeQueryRule custom QueryRule implementation.
17type userScopeQueryRule struct {
18 requiredScope ScopeSlug
19}
20
21func (r userScopeQueryRule) EvalQuery(ctx context.Context, q ent.Query) error {
22 user, err := getUserFromContext(ctx)
23 if err != nil {
24 return err
25 }
26
27 if userHasSystemScope(user, r.requiredScope) {
28 return privacy.Allow
29 }
30
31 return privacy.Skipf("user does not have required read scope: %s", r.requiredScope)
32}
33
34// UserWriteScopeRule checks write permissions.
35func UserWriteScopeRule(writeScope ScopeSlug) privacy.MutationRule {
36 return privacy.MutationRuleFunc(func(ctx context.Context, m ent.Mutation) error {
37 user, err := getUserFromContext(ctx)
38 if err != nil {
39 return err
40 }
41
42 if userHasSystemScope(user, writeScope) {
43 return privacy.Allow
44 }
45
46 return privacy.Skipf("user does not have required write scope: %s", writeScope)
47 })
48}
49
50// UserScopeQueryMutationRule checks both read and write permissions.
51func UserScopeQueryMutationRule(requiredScope ScopeSlug) privacy.QueryMutationRule {
52 return privacy.ContextQueryMutationRule(func(ctx context.Context) error {
53 user, err := getUserFromContext(ctx)
54 if err != nil {
55 return err
56 }
57
58 if userHasSystemScope(user, requiredScope) {
59 return privacy.Allow
60 }
61
62 return privacy.Skipf("user does not have required scope: %s", requiredScope)
63 })
64}
65
66func WithUserScopeDecision(ctx context.Context, requiredScope ScopeSlug) context.Context {
67 user, ok := contexts.GetUser(ctx)
68 if !ok || user == nil {
69 return privacy.DecisionContext(ctx, privacy.Deny)
70 }
71
72 if userHasSystemScope(user, requiredScope) {
73 return privacy.DecisionContext(ctx, privacy.Allow)
74 }
75
76 return privacy.DecisionContext(ctx, privacy.Deny)
77}
78
79func UserHasScope(ctx context.Context, requiredScope ScopeSlug) bool {
80 user, ok := contexts.GetUser(ctx)
81 if !ok || user == nil {
82 return false
83 }
84
85 if userHasSystemScope(user, requiredScope) {
86 return true
87 }
88
89 return false
90}
91 