|
| 1 | +package interceptor |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/rpsoftech/bullion-server/src/env" |
| 9 | + "google.golang.org/grpc" |
| 10 | + "google.golang.org/grpc/codes" |
| 11 | + "google.golang.org/grpc/metadata" |
| 12 | + "google.golang.org/grpc/status" |
| 13 | +) |
| 14 | + |
| 15 | +var ( |
| 16 | + errMissingMetadata = status.Errorf(codes.InvalidArgument, "missing metadata") |
| 17 | + errInvalidToken = status.Errorf(codes.Unauthenticated, "invalid token") |
| 18 | +) |
| 19 | + |
| 20 | +// func(ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler) (resp any, err error) |
| 21 | + |
| 22 | +func OAuth2Interceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { |
| 23 | + |
| 24 | + // return nil, nil |
| 25 | + md, ok := metadata.FromIncomingContext(ctx) |
| 26 | + if !ok { |
| 27 | + return nil, errMissingMetadata |
| 28 | + } |
| 29 | + if !valid(md[env.RequestTokenHeaderKey]) { |
| 30 | + return nil, errInvalidToken |
| 31 | + } |
| 32 | + m, err := handler(ctx, req) |
| 33 | + if err != nil { |
| 34 | + logger("RPC failed with error: %v", err) |
| 35 | + } |
| 36 | + return m, err |
| 37 | +} |
| 38 | +func logger(format string, a ...any) { |
| 39 | + fmt.Printf("LOG:\t"+format+"\n", a...) |
| 40 | +} |
| 41 | + |
| 42 | +func valid(authorization []string) bool { |
| 43 | + if len(authorization) < 1 { |
| 44 | + return false |
| 45 | + } |
| 46 | + token := strings.TrimPrefix(authorization[0], "Bearer ") |
| 47 | + println(authorization) |
| 48 | + // Perform the token validation here. For the sake of this example, the code |
| 49 | + // here forgoes any of the usual OAuth2 token validation and instead checks |
| 50 | + // for a token matching an arbitrary string. |
| 51 | + return token == "some-secret-token" |
| 52 | +} |
0 commit comments