2018-10-09 15:39:14 +01:00
|
|
|
// Copyright (C) 2018 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package grpcauth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
"google.golang.org/grpc/metadata"
|
|
|
|
|
|
|
|
"storj.io/storj/pkg/auth"
|
|
|
|
)
|
|
|
|
|
|
|
|
// NewAPIKeyInterceptor creates instance of apikey interceptor
|
|
|
|
func NewAPIKeyInterceptor() grpc.UnaryServerInterceptor {
|
|
|
|
return func(ctx context.Context, req interface{},
|
|
|
|
info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{},
|
|
|
|
err error) {
|
|
|
|
|
|
|
|
md, ok := metadata.FromIncomingContext(ctx)
|
2019-01-08 08:22:54 +00:00
|
|
|
if !ok {
|
2018-10-09 15:39:14 +01:00
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
2019-01-08 08:22:54 +00:00
|
|
|
apikeys, ok := md["apikey"]
|
|
|
|
if !ok || len(apikeys) == 0 {
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
return handler(auth.WithAPIKey(ctx, []byte(apikeys[0])), req)
|
2018-10-09 15:39:14 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewAPIKeyInjector injects api key to grpc connection context
|
2018-10-11 15:35:55 +01:00
|
|
|
func NewAPIKeyInjector(APIKey string, callOpts ...grpc.CallOption) grpc.UnaryClientInterceptor {
|
2018-10-09 15:39:14 +01:00
|
|
|
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
2018-10-11 15:35:55 +01:00
|
|
|
opts = append(opts, callOpts...)
|
2018-10-09 15:39:14 +01:00
|
|
|
ctx = metadata.AppendToOutgoingContext(ctx, "apikey", APIKey)
|
2018-10-11 15:35:55 +01:00
|
|
|
return invoker(ctx, method, req, reply, cc, opts...)
|
2018-10-09 15:39:14 +01:00
|
|
|
}
|
|
|
|
}
|