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.utils.translation import ugettext as _
16 from json import load as load_json
18 from django.utils.simplejson import JSONDecoder
21 decoder = JSONDecoder()
22 return decoder.decode(json.read())
24 class FacebookAuthConsumer(AuthenticationConsumer):
26 def prepare_authentication_request(self, request, redirect_to):
28 client_id=settings.FB_API_KEY,
29 redirect_uri="%s%s" % (django_settings.APP_URL, redirect_to),
33 facebook_api_authentication_url = "https://graph.facebook.com/oauth/authorize?" + urlencode(args)
35 return facebook_api_authentication_url
37 def process_authentication_request(self, request):
39 args = dict(client_id=settings.FB_API_KEY, redirect_uri="%s%s" % (django_settings.APP_URL, request.path))
41 args["client_secret"] = settings.FB_APP_SECRET #facebook APP Secret
43 args["code"] = request.GET.get("code", None)
44 response = cgi.parse_qs(urlopen("https://graph.facebook.com/oauth/access_token?" + urlencode(args)).read())
45 access_token = response["access_token"][-1]
47 # Store the access token in cookie
48 request.session["assoc_key"] = access_token
52 logging.error("Problem during facebook authentication: %s" % e)
53 raise InvalidAuthentication(_("Something wrond happened during Facebook authentication, administrators will be notified"))
55 def get_user_data(self, assoc_key):
56 profile = load_json(urlopen("https://graph.facebook.com/me?" + urlencode(dict(access_token=assoc_key))))
58 name = profile["name"]
60 # Check whether the length if the email is greater than 75, if it is -- just replace the email
61 # with a blank string variable, otherwise we're going to have trouble with the Django model.
62 email = smart_unicode(profile['email'])
66 # If the name is longer than 30 characters - leave it blank
70 # Return the user data.
76 class FacebookAuthContext(ConsumerTemplateContext):
80 human_name = 'Facebook'
81 code_template = 'modules/facebookauth/button.html'
84 API_KEY = settings.FB_API_KEY