forked from grpc-ecosystem/go-grpc-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
selector_example_test.go
84 lines (68 loc) · 2.53 KB
/
selector_example_test.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
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package selector_test
import (
"context"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/auth"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/ratelimit"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/selector"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// alwaysPassLimiter is an example limiter which implements Limiter interface.
// It does not limit any request because Limit function always returns false.
type alwaysPassLimiter struct{}
func (*alwaysPassLimiter) Limit(_ context.Context) error {
return nil
}
func healthSkip(_ context.Context, c interceptors.CallMeta) bool {
return c.FullMethod() != "/ping.v1.PingService/Health"
}
func Example_ratelimit() {
limiter := &alwaysPassLimiter{}
_ = grpc.NewServer(
grpc.ChainUnaryInterceptor(
selector.UnaryServerInterceptor(ratelimit.UnaryServerInterceptor(limiter), selector.MatchFunc(healthSkip)),
),
grpc.ChainStreamInterceptor(
selector.StreamServerInterceptor(ratelimit.StreamServerInterceptor(limiter), selector.MatchFunc(healthSkip)),
),
)
}
var tokenInfoKey struct{}
func parseToken(token string) (struct{}, error) {
return struct{}{}, nil
}
func userClaimFromToken(struct{}) string {
return "foobar"
}
// exampleAuthFunc is used by a middleware to authenticate requests
func exampleAuthFunc(ctx context.Context) (context.Context, error) {
token, err := auth.AuthFromMD(ctx, "bearer")
if err != nil {
return nil, err
}
tokenInfo, err := parseToken(token)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, "invalid auth token: %v", err)
}
ctx = logging.InjectFields(ctx, logging.Fields{"auth.sub", userClaimFromToken(tokenInfo)})
// WARNING: In production define your own type to avoid context collisions.
return context.WithValue(ctx, tokenInfoKey, tokenInfo), nil
}
func loginSkip(_ context.Context, c interceptors.CallMeta) bool {
return c.FullMethod() != "/auth.v1.AuthService/Login"
}
func Example_login() {
_ = grpc.NewServer(
grpc.ChainUnaryInterceptor(
selector.UnaryServerInterceptor(auth.UnaryServerInterceptor(exampleAuthFunc), selector.MatchFunc(loginSkip)),
),
grpc.ChainStreamInterceptor(
selector.StreamServerInterceptor(auth.StreamServerInterceptor(exampleAuthFunc), selector.MatchFunc(loginSkip)),
),
)
}