2019-01-24 20:15:10 +00:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
2018-10-09 15:39:14 +01:00
|
|
|
// 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)
|
|
|
|
}
|
2019-01-18 13:54:08 +00:00
|
|
|
|
2019-01-08 08:22:54 +00:00
|
|
|
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
|
2019-05-29 14:14:25 +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...)
|
2019-05-29 14:14:25 +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
|
|
|
}
|
|
|
|
}
|