-
Notifications
You must be signed in to change notification settings - Fork 0
/
interceptor.go
63 lines (51 loc) · 1.63 KB
/
interceptor.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
package auth
import (
"context"
"errors"
"github.com/duc-cnzj/execit/internal/contracts"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"google.golang.org/grpc"
)
func UnaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
if authorizeInterface, ok := info.Server.(contracts.AuthorizeInterface); ok {
ctx, err = authorizeInterface.Authorize(ctx, info.FullMethod)
if err != nil {
return nil, err
}
}
return handler(ctx, req)
}
}
func StreamServerInterceptor() grpc.StreamServerInterceptor {
return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
var (
newCtx context.Context
err error
)
if authorizeInterface, ok := srv.(contracts.AuthorizeInterface); ok {
newCtx, err = authorizeInterface.Authorize(ss.Context(), info.FullMethod)
if err != nil {
return err
}
wrapped := grpc_middleware.WrapServerStream(ss)
wrapped.WrappedContext = newCtx
return handler(srv, wrapped)
}
return handler(srv, ss)
}
}
type CtxTokenInfo struct{}
func SetUser(ctx context.Context, info *contracts.UserInfo) context.Context {
return context.WithValue(ctx, &CtxTokenInfo{}, info)
}
func GetUser(ctx context.Context) (*contracts.UserInfo, error) {
if info, ok := ctx.Value(&CtxTokenInfo{}).(*contracts.UserInfo); ok {
return info, nil
}
return nil, errors.New("user not found")
}
func MustGetUser(ctx context.Context) *contracts.UserInfo {
info, _ := ctx.Value(&CtxTokenInfo{}).(*contracts.UserInfo)
return info
}