]> git.openstreetmap.org Git - osqa.git/blob - forum_modules/facebookauth/authentication.py
adding support for the new Facebook oauth 2.0 authentication model
[osqa.git] / forum_modules / facebookauth / authentication.py
1 import hashlib
2 from time import time
3 from datetime import datetime
4 from urllib import urlopen,  urlencode
5 from urlparse import parse_qs
6 from forum.authentication.base import AuthenticationConsumer, ConsumerTemplateContext, InvalidAuthentication
7 from django.utils.translation import ugettext as _
8 from django.utils.encoding import smart_unicode
9
10 import settings
11
12 try:
13     from json import load as load_json
14 except:
15     from django.utils.simplejson import JSONDecoder
16
17     def load_json(json):
18         decoder = JSONDecoder()
19         return decoder.decode(json.read())
20
21 class FacebookAuthConsumer(AuthenticationConsumer):
22     
23     def process_authentication_request(self, request):
24         API_KEY = str(settings.FB_API_KEY)
25
26         # Check if the Facebook cookie has been received.
27         if 'fbs_%s' % API_KEY in request.COOKIES:
28             fbs_cookie = request.COOKIES['fbs_%s' % API_KEY]
29             parsed_fbs = parse_qs(smart_unicode(fbs_cookie))
30             self.parsed_fbs = parsed_fbs
31
32             # Check if the session hasn't expired.
33             if self.check_session_expiry(request.COOKIES):
34                 return parsed_fbs['uid'][0]
35             else:
36                 raise InvalidAuthentication(_('Sorry, your Facebook session has expired, please try again'))
37         else:
38             raise InvalidAuthentication(_('The authentication with Facebook connect failed, cannot find authentication tokens'))
39     def check_session_expiry(self, cookies):
40         return datetime.fromtimestamp(float(self.parsed_fbs['expires'][0])) > datetime.now()
41
42     def get_user_data(self, cookies):
43         API_KEY = str(settings.FB_API_KEY)
44         fbs_cookie = cookies['fbs_%s' % API_KEY]
45         parsed_fbs = parse_qs(smart_unicode(fbs_cookie))
46
47         # Communicate with the access token to the Facebook oauth interface.
48         json = load_json(urlopen('https://graph.facebook.com/me?access_token=%s' % parsed_fbs['access_token'][0]))
49
50         # Return the user data.
51         return {
52             'username': '%s %s' % (smart_unicode(json['first_name']), smart_unicode(json['last_name'])),
53             'email': smart_unicode(json['email']),
54         }
55
56 class FacebookAuthContext(ConsumerTemplateContext):
57     mode = 'BIGICON'
58     type = 'CUSTOM'
59     weight = 100
60     human_name = 'Facebook'
61     code_template = 'modules/facebookauth/button.html'
62     extra_css = ["http://www.facebook.com/css/connect/connect_button.css"]
63
64     API_KEY = settings.FB_API_KEY