Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(189)

Side by Side Diff: third_party/google-endpoints/oauth2client/devshell.py

Issue 2666783008: Add google-endpoints to third_party/. (Closed)
Patch Set: Created 3 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # Copyright 2015 Google Inc. All Rights Reserved.
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 """OAuth 2.0 utitilies for Google Developer Shell environment."""
16
17 import json
18 import os
19 import socket
20
21 from oauth2client._helpers import _to_bytes
22 from oauth2client import client
23
24 DEVSHELL_ENV = 'DEVSHELL_CLIENT_PORT'
25
26
27 class Error(Exception):
28 """Errors for this module."""
29 pass
30
31
32 class CommunicationError(Error):
33 """Errors for communication with the Developer Shell server."""
34
35
36 class NoDevshellServer(Error):
37 """Error when no Developer Shell server can be contacted."""
38
39 # The request for credential information to the Developer Shell client socket
40 # is always an empty PBLite-formatted JSON object, so just define it as a
41 # constant.
42 CREDENTIAL_INFO_REQUEST_JSON = '[]'
43
44
45 class CredentialInfoResponse(object):
46 """Credential information response from Developer Shell server.
47
48 The credential information response from Developer Shell socket is a
49 PBLite-formatted JSON array with fields encoded by their index in the
50 array:
51
52 * Index 0 - user email
53 * Index 1 - default project ID. None if the project context is not known.
54 * Index 2 - OAuth2 access token. None if there is no valid auth context.
55 """
56
57 def __init__(self, json_string):
58 """Initialize the response data from JSON PBLite array."""
59 pbl = json.loads(json_string)
60 if not isinstance(pbl, list):
61 raise ValueError('Not a list: ' + str(pbl))
62 pbl_len = len(pbl)
63 self.user_email = pbl[0] if pbl_len > 0 else None
64 self.project_id = pbl[1] if pbl_len > 1 else None
65 self.access_token = pbl[2] if pbl_len > 2 else None
66
67
68 def _SendRecv():
69 """Communicate with the Developer Shell server socket."""
70
71 port = int(os.getenv(DEVSHELL_ENV, 0))
72 if port == 0:
73 raise NoDevshellServer()
74
75 sock = socket.socket()
76 sock.connect(('localhost', port))
77
78 data = CREDENTIAL_INFO_REQUEST_JSON
79 msg = '%s\n%s' % (len(data), data)
80 sock.sendall(_to_bytes(msg, encoding='utf-8'))
81
82 header = sock.recv(6).decode()
83 if '\n' not in header:
84 raise CommunicationError('saw no newline in the first 6 bytes')
85 len_str, json_str = header.split('\n', 1)
86 to_read = int(len_str) - len(json_str)
87 if to_read > 0:
88 json_str += sock.recv(to_read, socket.MSG_WAITALL).decode()
89
90 return CredentialInfoResponse(json_str)
91
92
93 class DevshellCredentials(client.GoogleCredentials):
94 """Credentials object for Google Developer Shell environment.
95
96 This object will allow a Google Developer Shell session to identify its
97 user to Google and other OAuth 2.0 servers that can verify assertions. It
98 can be used for the purpose of accessing data stored under the user
99 account.
100
101 This credential does not require a flow to instantiate because it
102 represents a two legged flow, and therefore has all of the required
103 information to generate and refresh its own access tokens.
104 """
105
106 def __init__(self, user_agent=None):
107 super(DevshellCredentials, self).__init__(
108 None, # access_token, initialized below
109 None, # client_id
110 None, # client_secret
111 None, # refresh_token
112 None, # token_expiry
113 None, # token_uri
114 user_agent)
115 self._refresh(None)
116
117 def _refresh(self, http_request):
118 self.devshell_response = _SendRecv()
119 self.access_token = self.devshell_response.access_token
120
121 @property
122 def user_email(self):
123 return self.devshell_response.user_email
124
125 @property
126 def project_id(self):
127 return self.devshell_response.project_id
128
129 @classmethod
130 def from_json(cls, json_data):
131 raise NotImplementedError(
132 'Cannot load Developer Shell credentials from JSON.')
133
134 @property
135 def serialization_data(self):
136 raise NotImplementedError(
137 'Cannot serialize Developer Shell credentials.')
OLDNEW
« no previous file with comments | « third_party/google-endpoints/oauth2client/crypt.py ('k') | third_party/google-endpoints/oauth2client/django_orm.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698