1# Copyright 2017 gRPC authors. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Interceptor that ensures a specific header is present.""" 15 16import grpc 17 18 19def _unary_unary_rpc_terminator(code, details): 20 def terminate(ignored_request, context): 21 context.abort(code, details) 22 23 return grpc.unary_unary_rpc_method_handler(terminate) 24 25 26class RequestHeaderValidatorInterceptor(grpc.ServerInterceptor): 27 def __init__(self, header, value, code, details): 28 self._header = header 29 self._value = value 30 self._terminator = _unary_unary_rpc_terminator(code, details) 31 32 def intercept_service(self, continuation, handler_call_details): 33 if ( 34 self._header, 35 self._value, 36 ) in handler_call_details.invocation_metadata: 37 return continuation(handler_call_details) 38 else: 39 return self._terminator 40