1 """Copyright 2020 Deutsche Telekom.
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
7 http://www.apache.org/licenses/LICENSE-2.0
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.
15 from collections import namedtuple
16 from typing import Any, Callable, List
18 from grpc import ClientCallDetails, StreamStreamClientInterceptor
21 class NewClientCallDetails(
22 namedtuple("_ClientCallDetails", ("method", "timeout", "metadata", "credentials")), ClientCallDetails
24 """Namedtuple class to store metadata.
26 It's impossible to change original metadata in ClientCallDetails object
27 passed as a parameter to intercept method, so this class is going to get
28 original metadata tuple and add the authorization one.
34 class AuthTokenInterceptor(StreamStreamClientInterceptor):
35 """Interceptor class to set authorization header.
37 Set authorization header (but it can be any header also) for a gRPC call.
40 def __init__(self, token: str, header: str = "authorization") -> None:
41 """Initialize interceptor.
43 Set token and header which should be set into call. By default header is "authorization".
44 Header have to be lowercase.
47 token (str): Token value to be set.
48 header (str, optional): Header name. It must be lowercase. Defaults to "authorization".
50 self.token: str = token
51 if not header.islower():
52 raise ValueError("Header must be lowercase.")
53 self.header: str = header
55 def intercept_stream_stream(
56 self, continuation: Callable, client_call_details: ClientCallDetails, request_iterator: Any
58 """Add header into metadata."""
59 metadata: List = list(client_call_details.metadata) if client_call_details.metadata is not None else []
60 metadata.append((self.header, self.token,))
61 new_client_call_details: NewClientCallDetails = NewClientCallDetails(
62 client_call_details.method, client_call_details.timeout, metadata, client_call_details.credentials
64 return continuation(new_client_call_details, request_iterator)