-
Notifications
You must be signed in to change notification settings - Fork 0
/
interceptors.go
76 lines (61 loc) · 2.03 KB
/
interceptors.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
package grpcserver
import (
"context"
"os"
"github.com/google/uuid"
"github.com/rs/zerolog"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
type colabShieldContextKey string
const (
UserIdKey colabShieldContextKey = "userId"
ProjectIdKey colabShieldContextKey = "projectId"
RequestUUID colabShieldContextKey = "requestUUID"
)
var (
// TODO: Unauthenticated may not be the best code for these errors but should do for now.
ErrMissingMetadata = status.Error(codes.Unauthenticated, "missing metadata")
ErrMissingOrInvalidUserId = status.Error(codes.Unauthenticated, "missing or invalid userId")
ErrMissingOrInvalidProjectId = status.Error(codes.Unauthenticated, "missing or invalid projectId")
)
func UnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, ErrMissingMetadata
}
// Get userId and projectId from metadata
userIds := md.Get("userId")
if len(userIds) != 1 {
return nil, ErrMissingOrInvalidUserId
}
projectIds := md.Get("projectId")
if len(projectIds) != 1 {
return nil, ErrMissingOrInvalidProjectId
}
if userIds[0] == "" {
return nil, ErrMissingOrInvalidUserId
}
if projectIds[0] == "" {
return nil, ErrMissingOrInvalidProjectId
}
ctx = buildCollabShieldContext(ctx, userIds[0], projectIds[0], info.FullMethod)
resp, err := handler(ctx, req)
return resp, err
}
func buildCollabShieldContext(ctx context.Context, userId string, projectId string, method string) context.Context {
reqUUID := uuid.New().String()
ctx = context.WithValue(ctx, UserIdKey, userId)
ctx = context.WithValue(ctx, ProjectIdKey, projectId)
ctx = context.WithValue(ctx, RequestUUID, reqUUID)
logger := zerolog.New(os.Stdout).With().
Timestamp().
Str("uuid", reqUUID).
Str("userId", userId).
Str("projectId", projectId).
Str("method", method).
Logger()
return logger.WithContext(ctx)
}