1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 """Helpers for authentication using oauth2client or google-auth."""
16
17 try:
18 import google.auth
19 import google.auth.credentials
20 import google_auth_httplib2
21 HAS_GOOGLE_AUTH = True
22 except ImportError:
23 HAS_GOOGLE_AUTH = False
24
25 try:
26 import oauth2client
27 import oauth2client.client
28 HAS_OAUTH2CLIENT = True
29 except ImportError:
30 HAS_OAUTH2CLIENT = False
31
32 from googleapiclient.http import build_http
33
34
36 """Returns Application Default Credentials."""
37 if HAS_GOOGLE_AUTH:
38 credentials, _ = google.auth.default()
39 return credentials
40 elif HAS_OAUTH2CLIENT:
41 return oauth2client.client.GoogleCredentials.get_application_default()
42 else:
43 raise EnvironmentError(
44 'No authentication library is available. Please install either '
45 'google-auth or oauth2client.')
46
47
49 """Scopes the credentials if necessary.
50
51 Args:
52 credentials (Union[
53 google.auth.credentials.Credentials,
54 oauth2client.client.Credentials]): The credentials to scope.
55 scopes (Sequence[str]): The list of scopes.
56
57 Returns:
58 Union[google.auth.credentials.Credentials,
59 oauth2client.client.Credentials]: The scoped credentials.
60 """
61 if HAS_GOOGLE_AUTH and isinstance(
62 credentials, google.auth.credentials.Credentials):
63 return google.auth.credentials.with_scopes_if_required(
64 credentials, scopes)
65 else:
66 try:
67 if credentials.create_scoped_required():
68 return credentials.create_scoped(scopes)
69 else:
70 return credentials
71 except AttributeError:
72 return credentials
73
74
76 """Returns an http client that is authorized with the given credentials.
77
78 Args:
79 credentials (Union[
80 google.auth.credentials.Credentials,
81 oauth2client.client.Credentials]): The credentials to use.
82
83 Returns:
84 Union[httplib2.Http, google_auth_httplib2.AuthorizedHttp]: An
85 authorized http client.
86 """
87 if HAS_GOOGLE_AUTH and isinstance(
88 credentials, google.auth.credentials.Credentials):
89 return google_auth_httplib2.AuthorizedHttp(credentials,
90 http=build_http())
91 else:
92 return credentials.authorize(build_http())
93