codekingpro/portable-devtools
114k
1# Copyright 2022 Google LLC2#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 at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# 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 and13# limitations under the License.14 15"""Google API key support.16This module provides authentication using the `API key`_.17.. _API key:18 https://cloud.google.com/docs/authentication/api-keys/19"""20 21from google.auth import _helpers22from google.auth import credentials23from google.auth import exceptions24 25 26class Credentials(credentials.Credentials):27 """API key credentials.28 These credentials use API key to provide authorization to applications.29 """30 31 def __init__(self, token):32 """33 Args:34 token (str): API key string35 Raises:36 ValueError: If the provided API key is not a non-empty string.37 """38 super(Credentials, self).__init__()39 if not token:40 raise exceptions.InvalidValue("Token must be a non-empty API key string")41 self.token = token42 43 @property44 def expired(self):45 return False46 47 @property48 def valid(self):49 return True50 51 @_helpers.copy_docstring(credentials.Credentials)52 def refresh(self, request):53 return54 55 def apply(self, headers, token=None):56 """Apply the API key token to the x-goog-api-key header.57 Args:58 headers (Mapping): The HTTP request headers.59 token (Optional[str]): If specified, overrides the current access60 token.61 """62 headers["x-goog-api-key"] = token or self.token63 64 def before_request(self, request, method, url, headers):65 """Performs credential-specific before request logic.66 Refreshes the credentials if necessary, then calls :meth:`apply` to67 apply the token to the x-goog-api-key header.68 Args:69 request (google.auth.transport.Request): The object used to make70 HTTP requests.71 method (str): The request's HTTP method or the RPC method being72 invoked.73 url (str): The request's URI or the RPC service's URI.74 headers (Mapping): The request's headers.75 """76 self.apply(headers)77 