31 lines
963 B
Go
31 lines
963 B
Go
package mxgateway
|
|
|
|
import (
|
|
"context"
|
|
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/metadata"
|
|
)
|
|
|
|
const authorizationHeader = "authorization"
|
|
|
|
func unaryAuthInterceptor(apiKey string) grpc.UnaryClientInterceptor {
|
|
return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
|
return invoker(authContext(ctx, apiKey), method, req, reply, cc, opts...)
|
|
}
|
|
}
|
|
|
|
func streamAuthInterceptor(apiKey string) grpc.StreamClientInterceptor {
|
|
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
|
|
return streamer(authContext(ctx, apiKey), desc, cc, method, opts...)
|
|
}
|
|
}
|
|
|
|
func authContext(ctx context.Context, apiKey string) context.Context {
|
|
if apiKey == "" {
|
|
return ctx
|
|
}
|
|
|
|
return metadata.AppendToOutgoingContext(ctx, authorizationHeader, "Bearer "+apiKey)
|
|
}
|