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