Skip to content

Commit 3ce892e

Browse files
committed
refactor(graph): use same logic in applyQuestionVisibleScopeFilter
1 parent 2bb74d0 commit 3ce892e

File tree

2 files changed

+62
-50
lines changed

2 files changed

+62
-50
lines changed

graph/question.resolvers.go

Lines changed: 0 additions & 50 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

graph/questions_utils.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package graph
2+
3+
import (
4+
"context"
5+
"slices"
6+
"strings"
7+
8+
"github.com/database-playground/backend-v2/ent"
9+
entQuestion "github.com/database-playground/backend-v2/ent/question"
10+
"github.com/database-playground/backend-v2/graph/defs"
11+
"github.com/database-playground/backend-v2/internal/auth"
12+
)
13+
14+
// checkQuestionVisibleScope checks if the user has permission to access the question based on visible_scope.
15+
// Returns nil if the user has access, or an error (ErrNotFound) if they don't.
16+
func checkQuestionVisibleScope(ctx context.Context, question *ent.Question) error {
17+
visibleScope := question.VisibleScope
18+
// If visible_scope is empty, the question is visible to everyone
19+
if strings.TrimSpace(visibleScope) == "" {
20+
return nil
21+
}
22+
23+
// Get user from context
24+
tokenInfo, ok := auth.GetUser(ctx)
25+
if !ok {
26+
// If no user context, but question has visible_scope, return not found
27+
return defs.ErrNotFound
28+
}
29+
30+
// Check if user has the required scope
31+
for _, scope := range tokenInfo.Scopes {
32+
if scope == "*" || scope == visibleScope {
33+
return nil
34+
}
35+
}
36+
37+
return defs.ErrNotFound
38+
}
39+
40+
// applyQuestionVisibleScopeFilter applies visible_scope filtering to a question query.
41+
// If the user has wildcard scope "*", no filtering is applied.
42+
// Otherwise, only questions with nil visible_scope or visible_scope matching user's scopes are included.
43+
func applyQuestionVisibleScopeFilter(ctx context.Context, query *ent.QuestionQuery) *ent.QuestionQuery {
44+
tokenInfo, ok := auth.GetUser(ctx)
45+
if !ok {
46+
// If no user context, only show questions without visible_scope
47+
return query.Where(entQuestion.VisibleScopeIsNil())
48+
}
49+
50+
// If user has full access, don't filter
51+
if slices.Contains(tokenInfo.Scopes, "*") {
52+
return query
53+
}
54+
55+
// Filter to show only questions with nil visible_scope or visible_scope matching user's scopes
56+
return query.Where(
57+
entQuestion.Or(
58+
entQuestion.VisibleScopeIsNil(),
59+
entQuestion.VisibleScopeIn(tokenInfo.Scopes...),
60+
),
61+
)
62+
}

0 commit comments

Comments
 (0)