|
| 1 | +# Copyright 2022 Google LLC |
| 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 | + |
| 15 | +"""Google API key support. |
| 16 | +This module provides authentication using the `API key`_. |
| 17 | +.. _API key: |
| 18 | + https://cloud.google.com/docs/authentication/api-keys/ |
| 19 | +""" |
| 20 | + |
| 21 | +from google.auth import _helpers |
| 22 | +from google.auth import credentials |
| 23 | + |
| 24 | + |
| 25 | +class Credentials(credentials.Credentials): |
| 26 | + """API key credentials. |
| 27 | + These credentials use API key to provide authorization to applications. |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__(self, token): |
| 31 | + """ |
| 32 | + Args: |
| 33 | + token (str): API key string |
| 34 | + Raises: |
| 35 | + ValueError: If the provided API key is not a non-empty string. |
| 36 | + """ |
| 37 | + super(Credentials, self).__init__() |
| 38 | + if not token: |
| 39 | + raise ValueError("Token must be a non-empty API key string") |
| 40 | + self.token = token |
| 41 | + |
| 42 | + @property |
| 43 | + def expired(self): |
| 44 | + return False |
| 45 | + |
| 46 | + @property |
| 47 | + def valid(self): |
| 48 | + return True |
| 49 | + |
| 50 | + @_helpers.copy_docstring(credentials.Credentials) |
| 51 | + def refresh(self, request): |
| 52 | + return |
| 53 | + |
| 54 | + def apply(self, headers, token=None): |
| 55 | + """Apply the API key token to the x-goog-api-key header. |
| 56 | + Args: |
| 57 | + headers (Mapping): The HTTP request headers. |
| 58 | + token (Optional[str]): If specified, overrides the current access |
| 59 | + token. |
| 60 | + """ |
| 61 | + headers["x-goog-api-key"] = token or self.token |
| 62 | + |
| 63 | + def before_request(self, request, method, url, headers): |
| 64 | + """Performs credential-specific before request logic. |
| 65 | + Refreshes the credentials if necessary, then calls :meth:`apply` to |
| 66 | + apply the token to the x-goog-api-key header. |
| 67 | + Args: |
| 68 | + request (google.auth.transport.Request): The object used to make |
| 69 | + HTTP requests. |
| 70 | + method (str): The request's HTTP method or the RPC method being |
| 71 | + invoked. |
| 72 | + url (str): The request's URI or the RPC service's URI. |
| 73 | + headers (Mapping): The request's headers. |
| 74 | + """ |
| 75 | + self.apply(headers) |
0 commit comments