forked from wooyek/flask-social-blueprint
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathproviders.py
371 lines (322 loc) · 12.9 KB
/
providers.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# coding=utf-8
# Copyright 2013 Janusz Skonieczny
import logging
from flask_oauth import OAuthRemoteApp
from flask_babel import gettext as _
DEFAULT_PROPERTIES = ("user_id", "display_name",
"first_name", "last_name", "email", "image_url")
class BaseProvider(OAuthRemoteApp):
def __init__(self, *args, **kwargs):
super(BaseProvider, self).__init__(None, *args, **kwargs)
def get_profile(self, raw_data):
raise NotImplementedError()
class ExternalProfile(object):
def __init__(self, profile_id, data, raw_data):
self.id = profile_id
self.data = data
self.raw_data = raw_data
class Twitter(BaseProvider):
def __init__(self, *args, **kwargs):
defaults = {
'name': 'Twitter',
'base_url': 'http://api.twitter.com/1/',
'request_token_url': 'https://api.twitter.com/oauth/request_token',
'access_token_url': 'https://api.twitter.com/oauth/access_token',
'authorize_url': 'https://api.twitter.com/oauth/authenticate'
}
defaults.update(kwargs)
super(Twitter, self).__init__(*args, **defaults)
self.tokengetter(lambda: None)
def get_profile(self, raw_data):
logging.debug("data: %s" % raw_data)
import twitter
api = twitter.Api(consumer_key=self.consumer_key,
consumer_secret=self.consumer_secret,
access_token_key=raw_data['oauth_token'],
access_token_secret=raw_data['oauth_token_secret'],
cache=None)
profile = api.VerifyCredentials()
name_split = profile.name.split(" ", 1)
data = {
'provider': self.name,
'profile_id': str(profile.id),
'username': profile.screen_name,
"email": None, # twitter does not provide email
'access_token': raw_data['oauth_token'],
'secret': raw_data['oauth_token_secret'],
"first_name": name_split[0],
"last_name": name_split[1] if len(name_split) > 1 else None,
'cn': profile.name,
'profile_url': "http://twitter.com/{}".format(profile.screen_name),
'image_url': profile.profile_image_url
}
return ExternalProfile(str(profile.id), data, raw_data)
class Google(BaseProvider):
def __init__(self, *args, **kwargs):
defaults = {
'name': 'Google',
'base_url': 'https://www.google.com/accounts/',
'authorize_url': 'https://accounts.google.com/o/oauth2/auth',
'access_token_url': 'https://accounts.google.com/o/oauth2/token',
'request_token_url': None,
'access_token_method': 'POST',
'access_token_params': {
'grant_type': 'authorization_code'
},
'request_token_params': {
'response_type': 'code',
'scope': 'https://www.googleapis.com/auth/plus.me email'
}
}
defaults.update(kwargs)
super(Google, self).__init__(*args, **defaults)
def get_profile(self, raw_data):
access_token = raw_data['access_token']
import oauth2client.client as googleoauth
import apiclient.discovery as googleapi
import httplib2
credentials = googleoauth.AccessTokenCredentials(
access_token=access_token,
user_agent=''
)
http = httplib2.Http()
http = credentials.authorize(http)
api = googleapi.build('plus', 'v1', http=http)
profile = api.people().get(userId='me').execute()
name = profile.get('name')
data = {
'provider': "Google",
'profile_id': profile['id'],
'username': None,
"email": profile.get('emails')[0]["value"],
'access_token': access_token,
'secret': None,
"first_name": name.get("givenName"),
"last_name": name.get("familyName"),
'cn': profile.get('displayName'),
'profile_url': profile.get('url'),
'image_url': profile.get('image', {}).get("url")
}
return ExternalProfile(str(profile['id']), data, raw_data)
class Facebook(BaseProvider):
def __init__(self, *args, **kwargs):
defaults = {
'name': 'Facebook',
'base_url': 'https://graph.facebook.com/',
'request_token_url': None,
'access_token_url': '/oauth/access_token',
'authorize_url': 'https://www.facebook.com/dialog/oauth',
'request_token_params': {
'scope': 'email'
}
}
defaults.update(kwargs)
super(Facebook, self).__init__(*args, **defaults)
def get_profile(self, raw_data):
access_token = raw_data['access_token']
import facebook
graph = facebook.GraphAPI(access_token)
profile = graph.get_object("me")
profile_id = profile['id']
data = {
"provider": "Facebook",
"profile_id": profile_id,
"username": profile.get('username'),
"email": profile.get('email'),
"access_token": access_token,
"secret": None,
"first_name": profile.get('first_name'),
"last_name": profile.get('last_name'),
"cn": profile.get('name'),
"profile_url": ("http://facebook.com/profile.php?id={}"
.format(profile_id)),
"image_url": ("http://graph.facebook.com/{}/picture"
.format(profile_id)),
}
return ExternalProfile(profile_id, data, raw_data)
class Github(BaseProvider):
def __init__(self, *args, **kwargs):
defaults = {
'name': 'Github',
'base_url': 'https://github.com/',
'authorize_url': 'https://github.com/login/oauth/authorize',
'access_token_url': 'https://github.com/login/oauth/access_token',
'request_token_url': None,
'request_token_params': {
'response_type': 'code',
'scope': 'user:email'
}
}
defaults.update(kwargs)
super(Github, self).__init__(*args, **defaults)
def get_profile(self, raw_data):
logging.debug("raw_data: %s" % raw_data)
access_token = raw_data['access_token']
import requests
import json
r = requests.get('https://api.github.com/user?access_token={}'
.format(access_token))
if not r.ok:
raise Exception(_("Could not load profile data from Github API"))
profile = json.loads(r.text or r.content)
r = requests.get('https://api.github.com/user/emails?access_token={}'
.format(access_token))
if not r.ok:
raise Exception(_("Could not load emails data"
"from from Github API"))
emails = json.loads(r.text or r.content)
name_split = profile.get('name', "").split(" ", 1)
data = {
"provider": "Github",
"profile_id": str(profile["id"]),
"username": profile.get('login'),
"email": emails[0].get("email"),
"access_token": access_token,
"secret": None,
"first_name": name_split[0],
"last_name": name_split[1] if len(name_split) > 1 else None,
"cn": profile.get('name'),
"profile_url": profile["html_url"],
"image_url": profile["avatar_url"],
}
return ExternalProfile(str(profile['id']), data, raw_data)
class Douban(BaseProvider):
def __init__(self, *args, **kwargs):
defaults = {
'name': 'Douban',
'base_url': 'https://api.douban.com',
'authorize_url': 'https://www.douban.com/service/auth2/auth',
'request_token_params': {
'response_type': 'code',
'scope': 'douban_basic_common'
},
'access_token_url': 'https://www.douban.com/service/auth2/token',
'access_token_method': 'POST',
'access_token_params': {
'grant_type': 'authorization_code',
},
'request_token_url': None,
}
defaults.update(kwargs)
super(Douban, self).__init__(*args, **defaults)
def get_profile(self, raw_data):
logging.debug("raw_data: %s" % raw_data)
access_token = raw_data['access_token']
import requests
import json
header = {
'Authorization': "Bearer " + access_token,
}
r = requests.get('https://api.douban.com/v2/user/~me', headers=header)
if not r.ok:
raise Exception("Could not load profile data from Douban API")
profile = json.loads(r.text or r.content)
data = {
"provider": "Douban",
"profile_id": profile.get("id"),
"username": profile.get("uid"),
"cn": profile.get("name"),
"image_url": profile.get("avatar"),
"profile_url": profile.get("alt"),
"access_token": access_token,
"secret": None,
"email": None,
}
return ExternalProfile(profile.get('id'), data, raw_data)
class Weibo(BaseProvider):
def __init__(self, *args, **kwargs):
defaults = {
'name': 'Weibo',
'base_url': 'https://api.weibo.com',
'authorize_url': 'https://api.weibo.com/oauth2/authorize',
'request_token_params': {
'response_type': 'code'
},
'access_token_url': 'https://api.weibo.com/oauth2/access_token',
'access_token_method': 'POST',
'access_token_params': {
'grant_type': 'authorization_code',
},
'request_token_url': None,
}
defaults.update(kwargs)
super(Weibo, self).__init__(*args, **defaults)
def get_profile(self, raw_data):
logging.debug("raw_data: %s" % raw_data)
raw_data = eval(raw_data.keys()[0])
access_token = raw_data['access_token']
uid = raw_data['uid']
import requests
import json
r = requests.get(
'https://api.weibo.com/2/users/show.json?uid={}&access_token={}'
.format(uid, access_token))
if not r.ok:
raise Exception("Could not load profile data from Weibo API")
profile = json.loads(r.text or r.content)
data = {
"provider": "Weibo",
"profile_id": profile.get("id"),
"username": profile.get("screen_name"),
"cn": profile.get("name"),
"image_url": profile.get("avatar_large"),
"profile_url": "http://weibo.com/" + profile.get("domain"),
"access_token": access_token,
"secret": None,
"email": None,
}
return ExternalProfile(profile.get('id'), data, raw_data)
class QQ(BaseProvider):
def __init__(self, *args, **kwargs):
defaults = {
'name': 'QQ',
'base_url': 'https://graph.qq.com',
'authorize_url': 'https://graph.qq.com/oauth2.0/authorize',
'request_token_params': {
'response_type': 'code',
},
'access_token_url': 'https://graph.qq.com/oauth2.0/token',
'access_token_method': 'GET',
'access_token_params': {
'grant_type': 'authorization_code',
},
'request_token_url': None,
}
defaults.update(kwargs)
super(QQ, self).__init__(*args, **defaults)
def get_profile(self, raw_data):
access_token = raw_data['access_token']
import requests
import json
payload = {
'access_token': access_token,
}
r = requests.get('https://graph.qq.com/oauth2.0/me', params=payload)
if not r.ok:
raise Exception("Could not load profile data from QQ API")
import re
pattern = re.compile('openid":"(\w*)"}')
openid = pattern.search(r.text).groups()[0]
payload = {
'access_token': access_token,
'oauth_consumer_key': self.consumer_key,
'openid': openid,
'format': 'json',
}
r = requests.get('https://graph.qq.com/user/get_user_info',
params=payload)
if not r.ok:
raise Exception("Could not load profile data from QQ API")
profile = json.loads(r.text or r.content)
data = {
"provider": "QQ",
"profile_id": openid,
"username": profile.get("nickname"),
"cn": profile.get("nickname"),
"image_url": profile.get("figureurl"),
"profile_url": None,
"access_token": access_token,
"secret": None,
"email": None,
}
return ExternalProfile(openid, data, raw_data)