/
utils.py
351 lines (276 loc) · 11.4 KB
/
utils.py
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"""
Updated on 19.12.2009
@author: alen, pinda
Inspired by:
http://github.com/leah/python-oauth/blob/master/oauth/example/client.py
http://github.com/facebook/tornado/blob/master/tornado/auth.py
"""
import time
import base64
import urllib
import urllib2
# parse_qsl was moved from the cgi namespace to urlparse in Python2.6.
# this allows backwards compatibility
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
from xml.dom import minidom
import oauth2 as oauth
from openid.consumer import consumer as openid
from openid.consumer.discover import DiscoveryFailure
from openid.store.interface import OpenIDStore as OIDStore
from openid.association import Association as OIDAssociation
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.utils.translation import gettext as _
from django.conf import settings
from django.utils import simplejson
from django.contrib.sites.models import Site
from socialregistration.models import OpenIDStore as OpenIDStoreModel, OpenIDNonce
from urlparse import urlparse
USE_HTTPS = bool(getattr(settings, 'SOCIALREGISTRATION_USE_HTTPS', False))
def _https():
if USE_HTTPS:
return 's'
else:
return ''
class OpenIDStore(OIDStore):
max_nonce_age = 6 * 60 * 60
def storeAssociation(self, server_url, assoc=None):
stored_assoc = OpenIDStoreModel.objects.create(
server_url=server_url,
handle=assoc.handle,
secret=base64.encodestring(assoc.secret),
issued=assoc.issued,
lifetime=assoc.issued,
assoc_type=assoc.assoc_type
)
def getAssociation(self, server_url, handle=None):
stored_assocs = OpenIDStoreModel.objects.filter(
server_url=server_url
)
if handle:
stored_assocs = stored_assocs.filter(handle=handle)
stored_assocs.order_by('-issued')
if stored_assocs.count() == 0:
return None
return_val = None
for stored_assoc in stored_assocs:
assoc = OIDAssociation(
stored_assoc.handle, base64.decodestring(stored_assoc.secret),
stored_assoc.issued, stored_assoc.lifetime, stored_assoc.assoc_type
)
if assoc.getExpiresIn() == 0:
stored_assoc.delete()
else:
if return_val is None:
return_val = assoc
return return_val
def removeAssociation(self, server_url, handle):
stored_assocs = OpenIDStoreModel.objects.filter(
server_url=server_url
)
if handle:
stored_assocs = stored_assocs.filter(handle=handle)
stored_assocs.delete()
def useNonce(self, server_url, timestamp, salt):
try:
nonce = OpenIDNonce.objects.get(
server_url=server_url,
timestamp=timestamp,
salt=salt
)
except OpenIDNonce.DoesNotExist:
nonce = OpenIDNonce.objects.create(
server_url=server_url,
timestamp=timestamp,
salt=salt
)
return True
return False
class OpenID(object):
def __init__(self, request, return_to, endpoint):
"""
@param request: : django.http.HttpRequest object
@param return_to: URL to redirect back to once the user authenticated
the application on the OpenID provider
@param endpoint: URL to the OpenID provider we're connecting to
"""
self.request = request
self.return_to = return_to
self.endpoint = endpoint
self.store = OpenIDStore()
self.consumer = openid.Consumer(self.request.session, self.store)
self.result = None
def get_redirect(self):
auth_request = self.consumer.begin(self.endpoint)
redirect_url = auth_request.redirectURL(
'http%s://%s/' % (_https(), Site.objects.get_current().domain),
self.return_to
)
return HttpResponseRedirect(redirect_url)
def complete(self):
self.result = self.consumer.complete(
dict(self.request.GET.items()),
'http%s://%s%s' % (_https(), Site.objects.get_current(),
self.request.path)
)
def is_valid(self):
if self.result is None:
self.complete()
return self.result.status == openid.SUCCESS
def get_token_prefix(url):
"""
Returns a prefix for the token to store in the session so we can hold
more than one single oauth provider's access key in the session.
Example:
The request token url ``http://twitter.com/oauth/request_token``
returns ``twitter.com``
"""
try:
return urllib2.urlparse.urlparse(url).netloc
except AttributeError:
return urllib2.rulparse.urlparse(url)[1]
class OAuthError(Exception):
pass
class OAuthClient(object):
def __init__(self, request, consumer_key, consumer_secret, request_token_url,
access_token_url, authorization_url, callback_url, parameters=None):
self.request = request
self.request_token_url = request_token_url
self.access_token_url = access_token_url
self.authorization_url = authorization_url
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.consumer = oauth.Consumer(consumer_key, consumer_secret)
self.client = oauth.Client(self.consumer)
self.signature_method = oauth.SignatureMethod_HMAC_SHA1()
self.parameters = parameters
self.callback_url = callback_url
self.errors = []
self.request_token = None
self.access_token = None
def _get_request_token(self):
"""
Obtain a temporary request token to authorize an access token and to
sign the request to obtain the access token
"""
if self.request_token is None:
body = None
if self.callback_url is not None:
body = urllib.urlencode([
('oauth_callback', 'http://%s%s' % (
Site.objects.get_current(), reverse(self.callback_url)))
])
response, content = self.client.request(self.request_token_url,
"POST", body=body)
if response['status'] != '200':
raise OAuthError(
_('Invalid response while obtaining request token from "%s" - "%s".') % (get_token_prefix(self.request_token_url), content))
self.request_token = dict(parse_qsl(content))
self.request.session['oauth_%s_request_token' % get_token_prefix(self.request_token_url)] = self.request_token
return self.request_token
def _get_access_token(self):
"""
Obtain the access token to access private resources at the API endpoint.
"""
if self.access_token is None:
request_token = self._get_rt_from_session()
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
if self.callback_url is not None:
# If a callback_url is provided, the callback has to include a verifier.
token.set_verifier(self.request.GET.get('oauth_verifier'))
self.client = oauth.Client(self.consumer, token)
response, content = self.client.request(self.access_token_url, "POST")
if response['status'] != '200':
raise OAuthError(
_('Invalid response while obtaining access token from "%s" - "%s".') % (get_token_prefix(self.request_token_url), content))
self.access_token = dict(parse_qsl(content))
self.request.session['oauth_%s_access_token' % get_token_prefix(self.request_token_url)] = self.access_token
return self.access_token
def _get_rt_from_session(self):
"""
Returns the request token cached in the session by ``_get_request_token``
"""
try:
return self.request.session['oauth_%s_request_token' % get_token_prefix(self.request_token_url)]
except KeyError:
raise OAuthError(_('No request token saved for "%s".') % get_token_prefix(self.request_token_url))
def _get_authorization_url(self):
request_token = self._get_request_token()
return '%s?oauth_token=%s' % (self.authorization_url,
request_token['oauth_token'])
def is_valid(self):
try:
self._get_rt_from_session()
self._get_access_token()
except OAuthError, e:
self.errors.append(e.args[0])
return False
return True
def get_redirect(self):
"""
Returns a ``HttpResponseRedirect`` object to redirect the user to the
URL the OAuth provider handles authorization.
"""
return HttpResponseRedirect(self._get_authorization_url())
class OAuth(object):
"""
Base class to perform oauth signed requests from access keys saved in a user's
session.
See the ``OAuthTwitter`` class below for an example.
"""
def __init__(self, request, consumer_key, secret_key, request_token_url):
self.request = request
self.consumer_key = consumer_key
self.secret_key = secret_key
self.consumer = oauth.Consumer(consumer_key, secret_key)
self.request_token_url = request_token_url
def _get_rt_from_session(self):
"""
Returns the request token cached in the session by ``_get_request_token``
"""
try:
return self.request.session['oauth_%s_request_token' % get_token_prefix(self.request_token_url)]
except KeyError:
raise OAuthError(_('No request token saved for "%s".') % get_token_prefix(self.request_token_url))
request_token = property(_get_rt_from_session)
def _get_at_from_session(self):
"""
Get the saved access token for private resources from the session.
"""
try:
return self.request.session['oauth_%s_access_token' % get_token_prefix(self.request_token_url)]
except KeyError:
raise OAuthError(
_('No access token saved for "%s".') % get_token_prefix(self.request_token_url))
access_token = property(_get_at_from_session)
def query(self, url, method="GET", params=dict(), headers=dict()):
"""
Request a API endpoint at ``url`` with ``params`` being either the
POST or GET data.
"""
at = self.access_token
token = oauth.Token(at['oauth_token'], at['oauth_token_secret'])
client = oauth.Client(self.consumer, token)
body = urllib.urlencode(params)
response, content = client.request(url, method=method, headers=headers,
body=body)
if response['status'] != '200':
raise OAuthError(
_('No access to private resources at "%s".') % get_token_prefix(self.request_token_url))
return content
class OAuthTwitter(OAuth):
"""
Verifying twitter credentials
"""
url = 'https://twitter.com/account/verify_credentials.json'
def get_user_info(self):
user = simplejson.loads(self.query(self.url))
return user
class OAuthLinkedIn(OAuthTwitter):
"""
Verifying linkedin credentials
"""
url = "http://api.linkedin.com/v1/people/~:(id)?format=json"