-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient.py
More file actions
246 lines (194 loc) · 9.43 KB
/
client.py
File metadata and controls
246 lines (194 loc) · 9.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import oauth2 as oauth
import httplib2
import urllib
import urlparse
import re
import os
import os.path
import base64
import hmac
import hashlib
import json
from generate_api import SmartResponse, augment
import common.rdf_tools.rdf_ontology
import common.rdf_tools.util
KNOWN_SERVERS = {}
# Configuration file defining valid SMART API calls
class SMARTClientError(Exception):
pass
class SMARTClient(oauth.Client):
""" Establishes OAuth communication with an SMART Container, and provides access to the API. """
def __init__(self, app_id, api_base, consumer_params, **state_vars):
if consumer_params.get('consumer_key') is None \
or consumer_params.get('consumer_secret') is None:
raise SMARTClientError('We need both "consumer_key" and "consumer_secret" in the params dictionary, only got: %s' % consumer_params)
consumer = oauth.Consumer(consumer_params['consumer_key'], consumer_params['consumer_secret'])
super(SMARTClient, self).__init__(consumer)
self.app_id = app_id
self.api_base = api_base
self._record_id = None
# Set extra state that was passed in (i.e. record_id, app_email, etc.)
for var_name, value in state_vars.iteritems():
setattr(self, var_name, value)
if self.api_base not in KNOWN_SERVERS:
resp, content = self.get('manifest')
assert resp.status == 200, "Failed to fetch container manifest"
KNOWN_SERVERS[self.api_base] = json.loads(content)
self.container_manifest = KNOWN_SERVERS[self.api_base]
@property
def record_id(self):
return self._record_id
@record_id.setter
def record_id(self, new_record_id):
if self._record_id != new_record_id:
self._record_id = new_record_id
self.token = None
def loop_over_records(self):
"""Iterator allowing background apps to loop through each patient
record in the SMArt container, e.g. to perform reporting or analytics.
For each patient record in the container, sets access tokens on the
SmartClient object and yields the new record_id."""
r = self.post("/apps/%s/tokens/records/first" % self.app_id)
while r:
status = r[0].get('status')
if '200' != status:
if '404' == status:
break
raise Exception('Did not get token: %s (%s)' % (r[1], status))
# extract token from payload
p = {}
for pair in r[1].split('&'):
(k, v) = [urllib.unquote_plus(x) for x in pair.split('=')]
p[k]=v
# update ourselves and yield the record_id
record_id = p['smart_record_id']
self.record_id = record_id
self.update_token(p)
yield record_id
# prepare for next round
self.record_id = None
r = self.post("/apps/%s/tokens/records/%s/next" % (self.app_id, record_id))
def absolute_uri(self, uri):
if uri[:4] == "http":
return uri
while '/' == uri[:1]:
uri = uri[1:]
return '/'.join([self.api_base, uri])
@property
def launch_url(self):
""" Returns the start URL where the user can login and select a record
"""
url = self.container_manifest.get('launch_urls', {}).get('app_launch')
if url is None:
return None
# we must now substitute {{app_id}} with our id
return re.sub(r"\{\{\s*app_id\s*\}\}", self.app_id, url)
def get(self, uri, body={}, headers={}, **uri_params):
""" Make an OAuth-signed GET request to SMART Server. """
# append the body data to the querystring
if isinstance(body, dict) and len(body) > 0:
body = urllib.urlencode(body)
uri = "%s?%s" % (uri, body) if body else uri
uri_params = self._populated_request_params(uri_params)
return self.request(self.absolute_uri(uri), uri_params, method="GET", body='', headers=headers)
def put(self, uri, body='', headers={}, content_type=None, **uri_params):
""" Make an OAuth-signed PUT request to SMART Server. """
if content_type:
headers['Content-Type'] = content_type
# if our body is not plain, set the content type appropriately
if isinstance(body, dict):
body = urllib.urlencode(body)
headers['Content-Type'] = 'application/x-www-form-urlencoded'
uri_params = self._populated_request_params(uri_params)
return self.request(self.absolute_uri(uri), uri_params, method="PUT", body=body, headers=headers)
def post(self, uri, body='', headers={}, content_type=None, **uri_params):
""" Make an OAuth-signed POST request to SMART Server. """
if content_type:
headers['Content-Type'] = content_type
# if our body is not plain, set the content type appropriately
if isinstance(body, dict):
headers['Content-Type'] = 'application/x-www-form-urlencoded'
body = urllib.urlencode(body)
uri_params = self._populated_request_params(uri_params)
return self.request(self.absolute_uri(uri), uri_params, method="POST", body=body, headers=headers)
def delete(self, uri, headers={}, **uri_params):
""" Make an OAuth-signed DELETE request to SMART Server. """
uri_params = self._populated_request_params(uri_params)
return self.request(self.absolute_uri(uri), uri_params, method="DELETE", headers=headers)
def _populated_request_params(self, params):
""" Makes sure there is the app-id and record-id in the request parameters """
if params is None:
params = {}
if params.get('smart_app_id') is None:
params['smart_app_id'] = self.app_id
if params.get('smart_record_id') is None:
params['smart_record_id'] = self.record_id
return params
def update_token(self, resource_token):
""" Update the resource token used by the client to sign requests. """
if isinstance(resource_token, oauth.Token):
self.token = resource_token
else:
token = oauth.Token(resource_token['oauth_token'], resource_token['oauth_token_secret'])
self.token = token
def fetch_request_token(self, params={}):
""" Get a request token from the server. """
if self.token:
raise SMARTClientError("Client already has a resource token.")
# make sure we have the record id
if self.record_id is not None:
params['smart_record_id'] = self.record_id
# "oauth_callback" can only be "oob" anyway, so just set it
params['oauth_callback'] = 'oob'
resp, content = self.post(self.container_manifest['launch_urls']['request_token'], body=params)
if resp['status'] != '200':
raise SMARTClientError("%s response fetching request token: %s" % (resp['status'], content))
req_token = dict(urlparse.parse_qsl(content))
self.update_token(req_token)
return req_token
@property
def auth_redirect_url(self):
if not self.token:
raise SMARTClientError("Client must have a token to get a redirect url")
return self.container_manifest['launch_urls']['authorize_token'] + "?oauth_token=" + self.token.key
def exchange_token(self, verifier):
""" Exchange the client's current token (should be a request token) for an access token. """
if not self.token:
raise SMARTClientError("Client must have a token to exchange.")
self.token.set_verifier(verifier)
resp, content = self.post(self.container_manifest['launch_urls']['exchange_token'])
if resp['status'] != '200':
raise SMARTClientError("%s response fetching access token: %s"%(resp['status'], content))
access_token = dict(urlparse.parse_qsl(content))
self.update_token(access_token)
for var_name, value in access_token.iteritems():
if not var_name.startswith("oauth_"):
setattr(self, var_name, value)
return access_token
def get_surl_credentials(self):
""" Produces a token and secret for signing URLs."""
if not self.token:
raise SMARTClientError("Client must have a token to generate SURL credentials.")
secret = base64.b64encode(hmac.new(self.token.secret, "SURL-SECRET", hashlib.sha1).digest())
return {'token': self.token.key, 'secret': secret}
def _fill_url_template(self, url, **kwargs):
for param_name in re.findall("{(.*?)}", str(url)):
v = None
arg_name = param_name.lower()
try:
v = kwargs[arg_name]
except KeyError as e:
# Is it a direct attribute of the client? i.e. client.record_id
try:
v = getattr(self, arg_name)
except AttributeError:
raise KeyError("Expected argument %s" % arg_name)
if v is not None:
url = url.replace("{%s}" % param_name, unicode(v))
return url
def request(self, uri, uri_params, *args, **kwargs):
uri = self._fill_url_template(uri, **uri_params)
return super(SMARTClient, self).request(uri, *args, **kwargs)
if (not common.rdf_tools.rdf_ontology.parsed):
assert False, "No ontology found"
augment(SMARTClient)