-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathcontext.go
More file actions
62 lines (51 loc) · 1.65 KB
/
Copy pathcontext.go
File metadata and controls
62 lines (51 loc) · 1.65 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
package rbac
import (
"context"
"fmt"
"strings"
"github.com/openshift-online/rh-trex-ai/pkg/services"
)
type authResultKey struct{}
type AuthResult struct {
Username string
IsGlobalAdmin bool
ProjectIDs []string // nil = global access (all projects)
CredentialIDs []string // nil = global access (all credentials)
}
func SetAuthResult(ctx context.Context, result *AuthResult) context.Context {
return context.WithValue(ctx, authResultKey{}, result)
}
func GetAuthResult(ctx context.Context) *AuthResult {
v, _ := ctx.Value(authResultKey{}).(*AuthResult)
return v
}
// ApplyListFilter restricts list results to the caller's authorized scope.
// filterColumn is the DB column to filter on (e.g. "id" for projects, "project_id" for sessions).
// useCredentialIDs controls whether to filter by credential IDs instead of project IDs.
// Returns false if the user has zero authorized IDs (caller should return empty list).
func ApplyListFilter(ctx context.Context, listArgs *services.ListArguments, filterColumn string, useCredentialIDs bool) bool {
auth := GetAuthResult(ctx)
if auth == nil || auth.IsGlobalAdmin {
return true
}
var ids []string
if useCredentialIDs {
ids = auth.CredentialIDs
} else {
ids = auth.ProjectIDs
}
if len(ids) == 0 {
return false
}
quoted := make([]string, len(ids))
for i, id := range ids {
quoted[i] = fmt.Sprintf("'%s'", strings.ReplaceAll(id, "'", "''"))
}
scopeFilter := fmt.Sprintf("%s in (%s)", filterColumn, strings.Join(quoted, ","))
if listArgs.Search != "" {
listArgs.Search = fmt.Sprintf("(%s) and (%s)", listArgs.Search, scopeFilter)
} else {
listArgs.Search = scopeFilter
}
return true
}