Skip to content

Commit d88ef73

Browse files
kalil-pelissierkvlil
authored andcommitted
Add access token to internal context
* Extract access token from header * Inject access token in ctx * Refactor/split constants in separate file
1 parent 80215f4 commit d88ef73

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

pkg/trino/constants/keys.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package constants
2+
3+
const (
4+
AccessTokenKey = "accessToken"
5+
TrinoUserHeader = "X-Trino-User"
6+
)

pkg/trino/datasource-context.go

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,17 @@ package trino
33
import (
44
"context"
55
"fmt"
6+
"strings"
7+
68
"github.com/grafana/grafana-plugin-sdk-go/backend"
79
"github.com/grafana/grafana-plugin-sdk-go/backend/instancemgmt"
810
"github.com/grafana/sqlds/v2"
11+
"github.com/trinodb/grafana-trino/pkg/trino/constants"
912
"github.com/trinodb/grafana-trino/pkg/trino/models"
1013
)
1114

15+
const bearerPrefix = "Bearer "
16+
1217
type SQLDatasourceWithTrinoUserContext struct {
1318
sqlds.SQLDatasource
1419
}
@@ -21,13 +26,15 @@ func (ds *SQLDatasourceWithTrinoUserContext) QueryData(ctx context.Context, req
2126
return nil, fmt.Errorf("error reading settings: %s", err.Error())
2227
}
2328

29+
ctx = injectAccessToken(ctx, req)
30+
2431
if settings.EnableImpersonation {
2532
user := req.PluginContext.User
2633
if user == nil {
2734
return nil, fmt.Errorf("user can't be nil if impersonation is enabled")
2835
}
2936

30-
ctx = context.WithValue(ctx, "X-Trino-User", user)
37+
ctx = context.WithValue(ctx, constants.TrinoUserHeader, user)
3138
}
3239

3340
return ds.SQLDatasource.QueryData(ctx, req)
@@ -45,3 +52,21 @@ func NewDatasource(c sqlds.Driver) *SQLDatasourceWithTrinoUserContext {
4552
base := sqlds.NewDatasource(c)
4653
return &SQLDatasourceWithTrinoUserContext{*base}
4754
}
55+
56+
func extractBearerToken(header string) (string, bool) {
57+
if strings.HasPrefix(header, bearerPrefix) {
58+
return strings.TrimPrefix(header, bearerPrefix), true
59+
}
60+
return "", false
61+
}
62+
63+
func injectAccessToken(ctx context.Context, req *backend.QueryDataRequest) context.Context {
64+
header := req.GetHTTPHeader(backend.OAuthIdentityTokenHeaderName)
65+
66+
token, ok := extractBearerToken(header)
67+
if !ok {
68+
return ctx
69+
}
70+
71+
return context.WithValue(ctx, constants.AccessTokenKey, token)
72+
}

0 commit comments

Comments
 (0)