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
13 from json import load as load_json
15 from django.utils.simplejson import JSONDecoder
18 decoder = JSONDecoder()
19 return decoder.decode(json.read())
21 class FacebookAuthConsumer(AuthenticationConsumer):
23 def process_authentication_request(self, request):
24 API_KEY = str(settings.FB_API_KEY)
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
32 # Check if the session hasn't expired.
33 if self.check_session_expiry(request.COOKIES):
34 return parsed_fbs['uid'][0]
36 raise InvalidAuthentication(_('Sorry, your Facebook session has expired, please try again'))
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()
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))
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]))
50 # Return the user data.
52 'username': '%s %s' % (smart_unicode(json['first_name']), smart_unicode(json['last_name'])),
53 'email': smart_unicode(json['email']),
56 class FacebookAuthContext(ConsumerTemplateContext):
60 human_name = 'Facebook'
61 code_template = 'modules/facebookauth/button.html'
62 extra_css = ["http://www.facebook.com/css/connect/connect_button.css"]
64 API_KEY = settings.FB_API_KEY