forked from lukasjarosch/genki
-
Notifications
You must be signed in to change notification settings - Fork 1
/
metadata.go
84 lines (72 loc) · 1.76 KB
/
metadata.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package metadata
import (
"context"
"encoding/base64"
"strings"
"github.com/google/uuid"
"google.golang.org/grpc/metadata"
)
// Metadata is the internal metadata abstraction. It is used to provide a single way of handling metadata
// throughout different transport layers (gRPC, HTTP, AMQP, ...).
type Metadata map[string]string
type key struct{}
func FromContext(ctx context.Context) (Metadata, bool) {
md, ok := ctx.Value(key{}).(Metadata)
return md, ok
}
func NewContext(ctx context.Context, md Metadata) context.Context {
return context.WithValue(ctx, key{}, md)
}
func NewInternalContext(ctx context.Context) context.Context {
meta, _ := FromContext(ctx)
newMeta := make(Metadata)
replaced := false
for k, v := range meta {
if k == InternalKey {
newMeta[k] = "true"
replaced = true
} else {
newMeta[k] = v
}
}
if !replaced {
newMeta[InternalKey] = "true"
}
return NewContext(ctx, newMeta)
}
func NewOutgoingContext(ctx context.Context) context.Context {
md := metadata.MD{}
ctxMeta, ok := FromContext(ctx)
if ok {
for k, v := range ctxMeta {
if k == EmailKey || k == FirstNameKey || k == LastNameKey {
md.Set(k, base64.StdEncoding.EncodeToString([]byte(v)))
} else {
md.Set(k, v)
}
}
}
outCtx := metadata.NewOutgoingContext(ctx, md)
return outCtx
}
func NewRequestID() string {
return uuid.New().String()
}
func GetFromContext(ctx context.Context, key string) string {
md, ok := FromContext(ctx)
if !ok {
return ""
}
if val, ok := md[key]; ok {
return val
}
return ""
}
// HasRole returns true if the given role string occurs in metadata.roles
func HasRole(ctx context.Context, role string) bool {
roleString := GetFromContext(ctx, RolesKey)
if strings.Contains(roleString, role) {
return true
}
return false
}