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 first_name = smart_unicode(json['first_name'])
51 last_name = smart_unicode(json['last_name'])
52 full_name = '%s %s' % (first_name, last_name)
54 # There is a limit in the Django user model for the username length (no more than 30 characaters)
55 if len(full_name) <= 30:
57 # If the full name is too long use only the first
58 elif len(first_name) <= 30:
60 # If it's also that long -- only the last
61 elif len(last_name) <= 30:
63 # If the real name of the user is indeed that weird, let him choose something on his own =)
67 # Check whether the length if the email is greater than 75, if it is -- just replace the email
68 # with a blank string variable, otherwise we're going to have trouble with the Django model.
69 email = smart_unicode(json['email'])
73 # Return the user data.
79 class FacebookAuthContext(ConsumerTemplateContext):
83 human_name = 'Facebook'
84 code_template = 'modules/facebookauth/button.html'
87 API_KEY = settings.FB_API_KEY