/
oauth2.py
1821 lines (1400 loc) · 55.1 KB
/
oauth2.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
|oauth2| Providers
-------------------
Providers which implement the |oauth2|_ protocol.
.. autosummary::
OAuth2
Amazon
Behance
Bitly
Cosm
DeviantART
Eventbrite
Facebook
Foursquare
GitHub
Google
LinkedIn
PayPal
Reddit
Viadeo
VK
WindowsLive
Yammer
Yandex
"""
from authomatic.six.moves.urllib.parse import urlencode
import datetime
import logging
from authomatic import providers
from authomatic.exceptions import CancellationError, FailureError, OAuth2Error
import authomatic.core as core
__all__ = ['OAuth2', 'Amazon', 'Behance', 'Bitly', 'Cosm', 'DeviantART',
'Eventbrite', 'Facebook', 'Foursquare', 'GitHub', 'Google',
'LinkedIn', 'PayPal', 'Reddit', 'Viadeo', 'VK', 'WindowsLive',
'Yammer', 'Yandex']
class OAuth2(providers.AuthorizationProvider):
"""
Base class for |oauth2|_ providers.
"""
PROVIDER_TYPE_ID = 2
TOKEN_TYPES = ['', 'Bearer']
#: A scope preset to get most of the **user** info.
#: Use it in the :doc:`config` like ``{'scope': oauth2.Facebook.user_info_scope}``.
user_info_scope = []
#: :class:`bool` If ``False``, the provider doesn't support CSRF protection.
supports_csrf_protection = True
token_request_method = 'POST' # method for requesting an access token
def __init__(self, *args, **kwargs):
"""
Accepts additional keyword arguments:
:param list scope:
List of strings specifying requested permissions as described in the
`OAuth 2.0 spec <http://tools.ietf.org/html/rfc6749#section-3.3>`_.
:param bool offline:
If ``True`` the **provider** will be set up to request an *offline access token*.
default is ``False``.
As well as those inherited from :class:`.AuthorizationProvider` constructor.
"""
super(OAuth2, self).__init__(*args, **kwargs)
self.scope = self._kwarg(kwargs, 'scope', [])
self.offline = self._kwarg(kwargs, 'offline', False)
#===========================================================================
# Internal methods
#===========================================================================
def _x_scope_parser(self, scope):
"""
Override this to handle differences between accepted format of scope across providers.
:attr list scope:
List of scopes.
"""
# Most providers accept csv scope.
return ','.join(scope) if scope else ''
@classmethod
def create_request_elements(cls, request_type, credentials, url, method='GET', params=None,
headers=None, body='', secret=None, redirect_uri='', scope='', csrf=''):
"""
Creates |oauth2| request elements.
"""
headers = headers or {}
params = params or {}
consumer_key = credentials.consumer_key or ''
consumer_secret = credentials.consumer_secret or ''
token = credentials.token or ''
refresh_token = credentials.refresh_token or credentials.token or ''
# Separate url base and query parameters.
url, base_params = cls._split_url(url)
# Add params extracted from URL.
params.update(dict(base_params))
if request_type == cls.USER_AUTHORIZATION_REQUEST_TYPE:
# User authorization request.
# TODO: Raise error for specific message for each missing argument.
if consumer_key and redirect_uri and (csrf or not cls.supports_csrf_protection):
params['client_id'] = consumer_key
params['redirect_uri'] = redirect_uri
params['scope'] = scope
params['state'] = csrf
params['response_type'] = 'code'
# Add authorization header
headers.update(cls._authorization_header(credentials))
else:
raise OAuth2Error('Credentials with valid consumer_key and arguments redirect_uri, scope and ' + \
'state are required to create OAuth 2.0 user authorization request elements!')
elif request_type == cls.ACCESS_TOKEN_REQUEST_TYPE:
# Access token request.
if consumer_key and consumer_secret:
params['code'] = token
params['client_id'] = consumer_key
params['client_secret'] = consumer_secret
params['redirect_uri'] = redirect_uri
params['grant_type'] = 'authorization_code'
# TODO: Check whether all providers accept it
headers.update(cls._authorization_header(credentials))
else:
raise OAuth2Error('Credentials with valid token, consumer_key, consumer_secret and argument ' + \
'redirect_uri are required to create OAuth 2.0 access token request elements!')
elif request_type == cls.REFRESH_TOKEN_REQUEST_TYPE:
# Refresh access token request.
if refresh_token and consumer_key and consumer_secret:
params['refresh_token'] = refresh_token
params['client_id'] = consumer_key
params['client_secret'] = consumer_secret
params['grant_type'] = 'refresh_token'
else:
raise OAuth2Error('Credentials with valid refresh_token, consumer_key, consumer_secret ' + \
'are required to create OAuth 2.0 refresh token request elements!')
elif request_type == cls.PROTECTED_RESOURCE_REQUEST_TYPE:
# Protected resource request.
# Add Authorization header. See: http://tools.ietf.org/html/rfc6749#section-7.1
if credentials.token_type == cls.BEARER:
# http://tools.ietf.org/html/rfc6750#section-2.1
headers.update({'Authorization': 'Bearer {0}'.format(credentials.token)})
elif token:
params['access_token'] = token
else:
raise OAuth2Error('Credentials with valid token are required to create ' + \
'OAuth 2.0 protected resources request elements!')
request_elements = core.RequestElements(url, method, params, headers, body)
return cls._x_request_elements_filter(request_type, request_elements, credentials)
@staticmethod
def _x_refresh_credentials_if(credentials):
"""
Override this to specify conditions when it gives sense to refresh credentials.
.. warning::
|classmethod|
:param credentials:
:class:`.Credentials`
:returns:
``True`` or ``False``
"""
if credentials.refresh_token:
return True
#===========================================================================
# Exposed methods
#===========================================================================
@classmethod
def to_tuple(cls, credentials):
return (credentials.token,
credentials.refresh_token,
credentials.expiration_time,
cls.TOKEN_TYPES.index(credentials.token_type))
@classmethod
def reconstruct(cls, deserialized_tuple, credentials, cfg):
token, refresh_token, expiration_time, token_type = deserialized_tuple
credentials.token = token
credentials.refresh_token = refresh_token
credentials.expiration_time = expiration_time
credentials.token_type=cls.TOKEN_TYPES[int(token_type)]
return credentials
def refresh_credentials(self, credentials):
"""
Refreshes :class:`.Credentials` if it gives sense.
:param credentials:
:class:`.Credentials` to be refreshed.
:returns:
:class:`.Response`.
"""
if not self._x_refresh_credentials_if(credentials):
return
# We need consumer key and secret to make this kind of request.
cfg = credentials.config.get(credentials.provider_name)
credentials.consumer_key = cfg.get('consumer_key')
credentials.consumer_secret = cfg.get('consumer_secret')
request_elements = self.create_request_elements(request_type=self.REFRESH_TOKEN_REQUEST_TYPE,
credentials=credentials,
url=self.access_token_url,
method='POST')
self._log(logging.INFO, u'Refreshing credentials.')
response = self._fetch(*request_elements)
# We no longer need consumer info.
credentials.consumer_key = None
credentials.consumer_secret = None
# Extract the refreshed data.
access_token = response.data.get('access_token')
refresh_token = response.data.get('refresh_token')
# Update credentials only if there is access token.
if access_token:
credentials.token = access_token
credentials.expire_in = response.data.get('expires_in')
# Update refresh token only if there is a new one.
if refresh_token:
credentials.refresh_token = refresh_token
# Handle different naming conventions across providers.
credentials = self._x_credentials_parser(credentials, response.data)
return response
@providers.login_decorator
def login(self):
# get request parameters from which we can determine the login phase
authorization_code = self.params.get('code')
error = self.params.get('error')
error_message = self.params.get('error_message')
state = self.params.get('state')
if authorization_code or not self.user_authorization_url:
if authorization_code:
#===================================================================
# Phase 2 after redirect with success
#===================================================================
self._log(logging.INFO, u'Continuing OAuth 2.0 authorization procedure after redirect.')
# validate CSRF token
if self.supports_csrf_protection:
self._log(logging.INFO, u'Validating request by comparing request state with stored state.')
stored_state = self._session_get('state')
if not stored_state:
raise FailureError(u'Unable to retrieve stored state!')
elif not stored_state == state:
raise FailureError(u'The returned state "{0}" doesn\'t match with the stored state!'.format(state),
url=self.user_authorization_url)
self._log(logging.INFO, u'Request is valid.')
else:
self._log(logging.WARN, u'Skipping CSRF validation!')
elif not self.user_authorization_url:
#===================================================================
# Phase 1 without user authorization redirect.
#===================================================================
self._log(logging.INFO, u'Starting OAuth 2.0 authorization procedure without ' + \
u'user authorization redirect.')
# exchange authorization code for access token by the provider
self._log(logging.INFO, u'Fetching access token from {0}.'.format(self.access_token_url))
self.credentials.token = authorization_code
request_elements = self.create_request_elements(request_type=self.ACCESS_TOKEN_REQUEST_TYPE,
credentials=self.credentials,
url=self.access_token_url,
method=self.token_request_method,
redirect_uri=self.url,
params=self.access_token_params,
headers=self.access_token_headers)
response = self._fetch(*request_elements)
self.access_token_response = response
access_token = response.data.get('access_token', '')
refresh_token = response.data.get('refresh_token', '')
if response.status != 200 or not access_token:
raise FailureError('Failed to obtain OAuth 2.0 access token from {0}! HTTP status: {1}, message: {2}.'\
.format(self.access_token_url, response.status, response.content),
original_message=response.content,
status=response.status,
url=self.access_token_url)
self._log(logging.INFO, u'Got access token.')
if refresh_token:
self._log(logging.INFO, u'Got refresh access token.')
# OAuth 2.0 credentials need access_token, refresh_token, token_type and expire_in.
self.credentials.token = access_token
self.credentials.refresh_token = refresh_token
self.credentials.expire_in = response.data.get('expires_in')
self.credentials.token_type = response.data.get('token_type', '')
# sWe don't need these two guys anymore.
self.credentials.consumer_key = ''
self.credentials.consumer_secret = ''
# update credentials
self.credentials = self._x_credentials_parser(self.credentials, response.data)
# create user
self._update_or_create_user(response.data, self.credentials)
#===================================================================
# We're done!
#===================================================================
elif error or error_message:
#===================================================================
# Phase 2 after redirect with error
#===================================================================
error_reason = self.params.get('error_reason') or error
error_description = self.params.get('error_description') \
or error_message or error
if error_reason and 'denied' in error_reason:
raise CancellationError(error_description,
url=self.user_authorization_url)
else:
raise FailureError(error_description, url=self.user_authorization_url)
elif not self.params:
#===================================================================
# Phase 1 before redirect
#===================================================================
self._log(logging.INFO, u'Starting OAuth 2.0 authorization procedure.')
csrf = ''
if self.supports_csrf_protection:
# generate csfr
csrf = self.csrf_generator(self.settings.secret)
# and store it to session
self._session_set('state', csrf)
else:
self._log(logging.WARN, u'Provider doesn\'t support CSRF validation!')
request_elements = self.create_request_elements(request_type=self.USER_AUTHORIZATION_REQUEST_TYPE,
credentials=self.credentials,
url=self.user_authorization_url,
redirect_uri=self.url,
scope=self._x_scope_parser(self.scope),
csrf=csrf,
params=self.user_authorization_params)
self._log(logging.INFO, u'Redirecting user to {0}.'.format(request_elements.full_url))
self.redirect(request_elements.full_url)
class Amazon(OAuth2):
"""
Amazon |oauth2| provider.
Thanks to `Ghufran Syed <https://github.com/ghufransyed>`__.
* Dashboard: https://developer.amazon.com/lwa/sp/overview.html
* Docs: https://developer.amazon.com/public/apis/engage/login-with-amazon/docs/conceptual_overview.html
* API reference: https://developer.amazon.com/public/apis
.. note::
Amazon only accepts **redirect_uri** with **https** schema,
Therefore the *login handler* must also be accessible through **https**.
Supported :class:`.User` properties:
* email
* id
* name
* postal_code
Unsupported :class:`.User` properties:
* birth_date
* city
* country
* first_name
* gender
* last_name
* link
* locale
* nickname
* phone
* picture
* timezone
* username
"""
user_authorization_url = 'https://www.amazon.com/ap/oa'
access_token_url = 'https://api.amazon.com/auth/o2/token'
user_info_url = 'https://api.amazon.com/user/profile'
user_info_scope = ['profile', 'postal_code']
supported_user_attributes = core.SupportedUserAttributes(
email=True,
id=True,
name=True,
postal_code=True
)
def _x_scope_parser(self, scope):
# Amazon has space-separated scopes
return ' '.join(scope)
@staticmethod
def _x_user_parser(user, data):
user.id = data.get('user_id')
return user
@classmethod
def _x_credentials_parser(cls, credentials, data):
if data.get('token_type') == 'bearer':
credentials.token_type = cls.BEARER
return credentials
class Behance(OAuth2):
"""
Behance |oauth2| provider.
.. note::
Behance doesn't support third party authorization anymore,
which renders this class pretty much useless.
* Dashboard: http://www.behance.net/dev/apps
* Docs: http://www.behance.net/dev/authentication
* API reference: http://www.behance.net/dev/api/endpoints/
"""
user_authorization_url = 'https://www.behance.net/v2/oauth/authenticate'
access_token_url = 'https://www.behance.net/v2/oauth/token'
user_info_url = ''
user_info_scope = ['activity_read']
def _x_scope_parser(self, scope):
"""
Behance has pipe-separated scopes
"""
return '|'.join(scope)
@staticmethod
def _x_user_parser(user, data):
_user = data.get('user', {})
user.id = _user.get('id')
user.first_name = _user.get('first_name')
user.last_name = _user.get('last_name')
user.username = _user.get('username')
user.city = _user.get('city')
user.country = _user.get('country')
user.link = _user.get('url')
user.name = _user.get('display_name')
user.picture = _user.get('images', {}).get('138')
return user
class Bitly(OAuth2):
"""
Bitly |oauth2| provider.
.. warning::
|no-csrf|
* Dashboard: https://bitly.com/a/oauth_apps
* Docs: http://dev.bitly.com/authentication.html
* API reference: http://dev.bitly.com/api.html
Supported :class:`.User` properties:
* id
* link
* name
* picture
* username
Unsupported :class:`.User` properties:
* birth_date
* city
* country
* email
* first_name
* gender
* last_name
* locale
* nickname
* phone
* postal_code
* timezone
"""
supported_user_attributes = core.SupportedUserAttributes(
id=True,
link=True,
name=True,
picture=True,
username=True
)
supports_csrf_protection = False
_x_use_authorization_header = False
user_authorization_url = 'https://bitly.com/oauth/authorize'
access_token_url = 'https://api-ssl.bitly.com/oauth/access_token'
user_info_url = 'https://api-ssl.bitly.com/v3/user/info'
def __init__(self, *args, **kwargs):
super(Bitly, self).__init__(*args, **kwargs)
if self.offline:
if not 'grant_type' in self.access_token_params:
self.access_token_params['grant_type'] = 'refresh_token'
@staticmethod
def _x_user_parser(user, data):
info = data.get('data', {})
user.id = info.get('login')
user.name = info.get('full_name')
user.username = info.get('display_name')
user.picture = info.get('profile_image')
user.link = info.get('profile_url')
return user
class Cosm(OAuth2):
"""
Cosm |oauth2| provider.
.. note::
Cosm doesn't provide any *user info URL*.
* Dashboard: https://cosm.com/users/{your_username}/apps
* Docs: https://cosm.com/docs/
* API reference: https://cosm.com/docs/v2/
"""
user_authorization_url = 'https://cosm.com/oauth/authenticate'
access_token_url = 'https://cosm.com/oauth/token'
user_info_url = ''
@staticmethod
def _x_user_parser(user, data):
user.id = user.username = data.get('user')
return user
class DeviantART(OAuth2):
"""
DeviantART |oauth2| provider.
* Dashboard: https://www.deviantart.com/settings/myapps
* Docs: https://www.deviantart.com/developers/authentication
* API reference: http://www.deviantart.com/developers/oauth2
Supported :class:`.User` properties:
* name
* picture
* username
Unsupported :class:`.User` properties:
* birth_date
* city
* country
* email
* first_name
* gender
* id
* last_name
* link
* locale
* nickname
* phone
* postal_code
* timezone
"""
user_authorization_url = 'https://www.deviantart.com/oauth2/draft15/authorize'
access_token_url = 'https://www.deviantart.com/oauth2/draft15/token'
user_info_url = 'https://www.deviantart.com/api/oauth2/user/whoami'
user_info_scope = ['basic']
supported_user_attributes = core.SupportedUserAttributes(
name=True,
picture=True,
username=True
)
def __init__(self, *args, **kwargs):
super(DeviantART, self).__init__(*args, **kwargs)
if self.offline:
if not 'grant_type' in self.access_token_params:
self.access_token_params['grant_type'] = 'refresh_token'
@staticmethod
def _x_user_parser(user, data):
user.picture = data.get('usericonurl')
return user
class Eventbrite(OAuth2):
"""
Eventbrite |oauth2| provider.
Thanks to `Paul Brown <http://www.paulsprogrammingnotes.com/>`__.
* Dashboard: http://www.eventbrite.com/myaccount/apps/
* Docs: https://developer.eventbrite.com/docs/auth/
* API: http://developer.eventbrite.com/docs/
Supported :class:`.User` properties:
* email
* first_name
* id
* last_name
* name
Unsupported :class:`.User` properties:
* birth_date
* city
* country
* gender
* link
* locale
* nickname
* phone
* picture
* postal_code
* timezone
* username
"""
user_authorization_url = 'https://www.eventbrite.com/oauth/authorize'
access_token_url = 'https://www.eventbrite.com/oauth/token'
user_info_url = 'https://www.eventbriteapi.com/v3/users/me'
supported_user_attributes = core.SupportedUserAttributes(
email=True,
first_name=True,
id=True,
last_name=True,
name=True,
)
@classmethod
def _x_credentials_parser(cls, credentials, data):
if data.get('token_type') == 'bearer':
credentials.token_type = cls.BEARER
return credentials
@staticmethod
def _x_user_parser(user, data):
for email in data.get('emails', []):
if email.get('primary'):
user.email = email.get('email')
break
return user
class Facebook(OAuth2):
"""
Facebook |oauth2| provider.
* Dashboard: https://developers.facebook.com/apps
* Docs: http://developers.facebook.com/docs/howtos/login/server-side-login/
* API reference: http://developers.facebook.com/docs/reference/api/
* API explorer: http://developers.facebook.com/tools/explorer
Supported :class:`.User` properties:
* birth_date
* city
* country
* email
* first_name
* gender
* id
* last_name
* link
* locale
* location
* name
* picture
* timezone
Unsupported :class:`.User` properties:
* nickname
* phone
* postal_code
* username
"""
user_authorization_url = 'https://www.facebook.com/dialog/oauth'
access_token_url = 'https://graph.facebook.com/oauth/access_token'
user_info_url = 'https://graph.facebook.com/v2.3/me'
user_info_scope = ['email', 'user_about_me', 'user_birthday',
'user_location']
same_origin = False
supported_user_attributes = core.SupportedUserAttributes(
birth_date=True,
city=True,
country=True,
email=True,
first_name=True,
gender=True,
id=True,
last_name=True,
link=True,
locale=True,
location=True,
name=True,
picture=True,
timezone=True
)
@classmethod
def _x_request_elements_filter(cls, request_type, request_elements,
credentials):
if request_type == cls.REFRESH_TOKEN_REQUEST_TYPE:
# As always, Facebook has it's original name for "refresh_token"!
url, method, params, headers, body = request_elements
params['fb_exchange_token'] = params.pop('refresh_token')
params['grant_type'] = 'fb_exchange_token'
request_elements = core.RequestElements(url, method, params,
headers, body)
return request_elements
def __init__(self, *args, **kwargs):
super(Facebook, self).__init__(*args, **kwargs)
# Handle special Facebook requirements to be able
# to refresh the access token.
if self.offline:
# Facebook needs an offline_access scope.
if not 'offline_access' in self.scope:
self.scope.append('offline_access')
if self.popup:
self.user_authorization_url += '?display=popup'
@staticmethod
def _x_user_parser(user, data):
_birth_date = data.get('birthday')
if _birth_date:
try:
user.birth_date = datetime.datetime.strptime(_birth_date,
'%m/%d/%Y')
except ValueError:
pass
user.picture = ('http://graph.facebook.com/{0}/picture?type=large'
.format(user.id))
user.location = data.get('location', {}).get('name')
if user.location:
split_location = user.location.split(', ')
user.city = split_location[0].strip()
if len(split_location) > 1:
user.country = split_location[1].strip()
return user
@staticmethod
def _x_credentials_parser(credentials, data):
"""
We need to override this method to fix Facebooks naming deviation.
"""
# Facebook returns "expires" instead of "expires_in".
credentials.expire_in = data.get('expires')
return credentials
@staticmethod
def _x_refresh_credentials_if(credentials):
# Always refresh.
return True
class Foursquare(OAuth2):
"""
Foursquare |oauth2| provider.
* Dashboard: https://foursquare.com/developers/apps
* Docs: https://developer.foursquare.com/overview/auth.html
* API reference: https://developer.foursquare.com/docs/
.. note::
Foursquare requires a *version* parameter in each request.
The default value is ``v=20140501``. You can override the version in
the ``params`` parameter of the :meth:`.Authomatic.access` method.
See https://developer.foursquare.com/overview/versioning
Supported :class:`.User` properties:
* city
* country
* email
* first_name
* gender
* id
* last_name
* location
* name
* phone
* picture
Unsupported :class:`.User` properties:
* birth_date
* link
* locale
* nickname
* postal_code
* timezone
* username
"""
user_authorization_url = 'https://foursquare.com/oauth2/authenticate'
access_token_url = 'https://foursquare.com/oauth2/access_token'
user_info_url = 'https://api.foursquare.com/v2/users/self'
same_origin = False
supported_user_attributes = core.SupportedUserAttributes(
birth_date=True,
city=True,
country=True,
email=True,
first_name=True,
gender=True,
id=True,
last_name=True,
location=True,
name=True,
phone=True,
picture=True
)
@classmethod
def _x_request_elements_filter(cls, request_type, request_elements,
credentials):
if request_type == cls.PROTECTED_RESOURCE_REQUEST_TYPE:
# Foursquare uses OAuth 1.0 "oauth_token" for what should be
# "access_token" in OAuth 2.0!
url, method, params, headers, body = request_elements
params['oauth_token'] = params.pop('access_token')
# Foursquare needs the version "v" parameter in every request.
# https://developer.foursquare.com/overview/versioning
if not params.get('v'):
params['v'] = '20140501'
request_elements = core.RequestElements(url, method, params,
headers, body)
return request_elements
@staticmethod
def _x_user_parser(user, data):
_resp = data.get('response', {})
_user = _resp.get('user', {})
user.id = _user.get('id')
user.first_name = _user.get('firstName')
user.last_name = _user.get('lastName')
user.gender = _user.get('gender')
_birth_date = _user.get('birthday')
if _birth_date:
user.birth_date = datetime.datetime.fromtimestamp(_birth_date)
_photo = _user.get('photo', {})
if isinstance(_photo, dict):
_photo_prefix = _photo.get('prefix', '').strip('/')
_photo_suffix = _photo.get('suffix', '').strip('/')
user.picture = '/'.join([_photo_prefix, _photo_suffix])
if isinstance(_photo, str):
user.picture = _photo
user.location = _user.get('homeCity')
if user.location:
split_location = user.location.split(',')
user.city = split_location[0].strip()
if len(user.location) > 1:
user.country = split_location[1].strip()
_contact = _user.get('contact', {})
user.email = _contact.get('email')
user.phone = _contact.get('phone')
return user
class GitHub(OAuth2):
"""
GitHub |oauth2| provider.
* Dashboard: https://github.com/settings/developers
* Docs: http://developer.github.com/v3/#authentication
* API reference: http://developer.github.com/v3/
.. note::