1 # -*- coding: utf-8 -*-
6 from urllib import urlopen, urlencode
7 from forum.authentication.base import AuthenticationConsumer, ConsumerTemplateContext, InvalidAuthentication
9 from django.conf import settings as django_settings
10 from django.utils.encoding import smart_unicode
11 from django.core.urlresolvers import reverse
12 from django.utils.translation import ugettext as _
16 from json import load as load_json
19 class FacebookAuthConsumer(AuthenticationConsumer):
21 def prepare_authentication_request(self, request, redirect_to):
23 client_id=settings.FB_API_KEY,
24 redirect_uri="%s%s" % (django_settings.APP_URL, redirect_to),
28 facebook_api_authentication_url = "https://graph.facebook.com/oauth/authorize?" + urlencode(args)
30 return facebook_api_authentication_url
32 def process_authentication_request(self, request):
34 redirect_uri = "%s%s" % (django_settings.APP_URL, reverse('auth_provider_done', prefix='/', kwargs={'provider': 'facebook'}))
35 args = dict(client_id=settings.FB_API_KEY, redirect_uri=redirect_uri)
37 args["client_secret"] = settings.FB_APP_SECRET #facebook APP Secret
39 args["code"] = request.GET.get("code", None)
40 response = cgi.parse_qs(urlopen("https://graph.facebook.com/oauth/access_token?" + urlencode(args)).read())
41 access_token = response["access_token"][-1]
44 user_data = self.get_user_data(access_token)
45 assoc_key = user_data["id"]
47 # Store the access token in cookie
48 request.session["access_token"] = access_token
49 request.session["assoc_key"] = assoc_key
51 # Return the association key
54 logging.error("Problem during facebook authentication: %s" % e)
55 raise InvalidAuthentication(_("Something wrond happened during Facebook authentication, administrators will be notified"))
57 def get_user_data(self, access_token):
58 profile = load_json(urlopen("https://graph.facebook.com/me?" + urlencode(dict(access_token=access_token))))
60 name = profile["name"]
62 # Check whether the length if the email is greater than 75, if it is -- just replace the email
63 # with a blank string variable, otherwise we're going to have trouble with the Django model.
64 email = smart_unicode(profile['email'])
68 # If the name is longer than 30 characters - leave it blank
72 # 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