-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathtoken.go
59 lines (49 loc) · 1.29 KB
/
token.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
51
52
53
54
55
56
57
58
59
package context
import (
"context"
"fmt"
"github.com/influxdata/influxdb"
)
type contextKey string
const (
authorizerCtxKey contextKey = "influx/authorizer/v1"
)
// SetAuthorizer sets an authorizer on context.
func SetAuthorizer(ctx context.Context, a influxdb.Authorizer) context.Context {
return context.WithValue(ctx, authorizerCtxKey, a)
}
// GetAuthorizer retrieves an authorizer from context.
func GetAuthorizer(ctx context.Context) (influxdb.Authorizer, error) {
a, ok := ctx.Value(authorizerCtxKey).(influxdb.Authorizer)
if !ok {
return nil, &influxdb.Error{
Msg: "authorizer not found on context",
Code: influxdb.EInternal,
}
}
if a == nil {
return nil, &influxdb.Error{
Code: influxdb.EInternal,
Msg: "unexpected invalid authorizer",
}
}
return a, nil
}
// GetToken retrieves a token from the context; errors if no token.
func GetToken(ctx context.Context) (string, error) {
a, ok := ctx.Value(authorizerCtxKey).(influxdb.Authorizer)
if !ok {
return "", &influxdb.Error{
Msg: "authorizer not found on context",
Code: influxdb.EInternal,
}
}
auth, ok := a.(*influxdb.Authorization)
if !ok {
return "", &influxdb.Error{
Msg: fmt.Sprintf("authorizer not an authorization but a %T", a),
Code: influxdb.EInternal,
}
}
return auth.Token, nil
}