]> git.openstreetmap.org Git - osqa.git/blobdiff - forum_modules/facebookauth/authentication.py
Add README to the source code
[osqa.git] / forum_modules / facebookauth / authentication.py
old mode 100755 (executable)
new mode 100644 (file)
index f2c5b6b..8562bad
@@ -1,85 +1,91 @@
-import hashlib\r
-from time import time\r
-from datetime import datetime\r
-from urllib import urlopen,  urlencode\r
-from forum.authentication.base import AuthenticationConsumer, ConsumerTemplateContext, InvalidAuthentication\r
-from django.utils.translation import ugettext as _\r
-\r
-import settings\r
-\r
-try:\r
-    from json import load as load_json\r
-except:\r
-    from django.utils.simplejson import JSONDecoder\r
-\r
-    def load_json(json):\r
-        decoder = JSONDecoder()\r
-        return decoder.decode(json.read())\r
-\r
-class FacebookAuthConsumer(AuthenticationConsumer):\r
-    \r
-    def process_authentication_request(self, request):\r
-        API_KEY = settings.FB_API_KEY\r
-\r
-        if API_KEY in request.COOKIES:\r
-            if self.check_cookies_signature(request.COOKIES):\r
-                if self.check_session_expiry(request.COOKIES):\r
-                    return request.COOKIES[API_KEY + '_user']\r
-                else:\r
-                    raise InvalidAuthentication(_('Sorry, your Facebook session has expired, please try again'))\r
-            else:\r
-                raise InvalidAuthentication(_('The authentication with Facebook connect failed due to an invalid signature'))\r
-        else:\r
-            raise InvalidAuthentication(_('The authentication with Facebook connect failed, cannot find authentication tokens'))\r
-\r
-    def generate_signature(self, values):\r
-        keys = []\r
-\r
-        for key in sorted(values.keys()):\r
-            keys.append(key)\r
-\r
-        signature = ''.join(['%s=%s' % (key,  values[key]) for key in keys]) + settings.FB_APP_SECRET\r
-        return hashlib.md5(signature).hexdigest()\r
-\r
-    def check_session_expiry(self, cookies):\r
-        return datetime.fromtimestamp(float(cookies[settings.FB_API_KEY+'_expires'])) > datetime.now()\r
-\r
-    def check_cookies_signature(self, cookies):\r
-        API_KEY = settings.FB_API_KEY\r
-\r
-        values = {}\r
-\r
-        for key in cookies.keys():\r
-            if (key.startswith(API_KEY + '_')):\r
-                values[key.replace(API_KEY + '_',  '')] = cookies[key]\r
-\r
-        return self.generate_signature(values) == cookies[API_KEY]\r
-\r
-    def get_user_data(self, key):\r
-        request_data = {\r
-            'method': 'Users.getInfo',\r
-            'api_key': settings.FB_API_KEY,\r
-            'call_id': time(),\r
-            'v': '1.0',\r
-            'uids': key,\r
-            'fields': 'name,first_name,last_name,email',\r
-            'format': 'json',\r
-        }\r
-\r
-        request_data['sig'] = self.generate_signature(request_data)\r
-        fb_response = load_json(urlopen(settings.REST_SERVER, urlencode(request_data)))[0]\r
-\r
-        return {\r
-            'username': fb_response['first_name'] + ' ' + fb_response['last_name'],\r
-            'email': fb_response['email']\r
-        }\r
-\r
-class FacebookAuthContext(ConsumerTemplateContext):\r
-    mode = 'BIGICON'\r
-    type = 'CUSTOM'\r
-    weight = 100\r
-    human_name = 'Facebook'\r
-    code_template = 'modules/facebookauth/button.html'\r
-    extra_css = ["http://www.facebook.com/css/connect/connect_button.css"]\r
-\r
-    API_KEY = settings.FB_API_KEY
\ No newline at end of file
+# -*- coding: utf-8 -*-
+
+import cgi
+import logging
+
+from urllib import urlopen,  urlencode
+from forum.authentication.base import AuthenticationConsumer, ConsumerTemplateContext, InvalidAuthentication
+
+from django.conf import settings as django_settings
+from django.utils.encoding import smart_unicode
+from django.utils.translation import ugettext as _
+
+import settings
+
+try:
+    from json import load as load_json
+except Exception:
+    from django.utils.simplejson import JSONDecoder
+
+    def load_json(json):
+        decoder = JSONDecoder()
+        return decoder.decode(json.read())
+
+class FacebookAuthConsumer(AuthenticationConsumer):
+
+    def prepare_authentication_request(self, request, redirect_to):
+        args = dict(
+            client_id=settings.FB_API_KEY,
+            redirect_uri="%s%s" % (django_settings.APP_URL, redirect_to),
+            scope="email"
+        )
+
+        facebook_api_authentication_url = "https://graph.facebook.com/oauth/authorize?" + urlencode(args)
+
+        return facebook_api_authentication_url
+    
+    def process_authentication_request(self, request):
+        try:
+            args = dict(client_id=settings.FB_API_KEY, redirect_uri="%s%s" % (django_settings.APP_URL, request.path))
+
+            args["client_secret"] = settings.FB_APP_SECRET  #facebook APP Secret
+
+            args["code"] = request.GET.get("code", None)
+            response = cgi.parse_qs(urlopen("https://graph.facebook.com/oauth/access_token?" + urlencode(args)).read())
+            access_token = response["access_token"][-1]
+
+
+            user_data = self.get_user_data(access_token)
+            assoc_key = user_data["id"]
+
+            # Store the access token in cookie
+            request.session["access_token"] = access_token
+            request.session["assoc_key"] = assoc_key
+
+            # Return the association key
+            return assoc_key
+        except Exception, e:
+            logging.error("Problem during facebook authentication: %s" % e)
+            raise InvalidAuthentication(_("Something wrond happened during Facebook authentication, administrators will be notified"))
+
+    def get_user_data(self, access_token):
+        profile = load_json(urlopen("https://graph.facebook.com/me?" + urlencode(dict(access_token=access_token))))
+
+        name = profile["name"]
+
+        # Check whether the length if the email is greater than 75, if it is -- just replace the email
+        # with a blank string variable, otherwise we're going to have trouble with the Django model.
+        email = smart_unicode(profile['email'])
+        if len(email) > 75:
+            email = ''
+
+        # If the name is longer than 30 characters - leave it blank
+        if len(name) > 30:
+            name = ''
+
+        # Return the user data.
+        return {
+            'id' : profile['id'],
+            'username': name,
+            'email': email,
+        }
+
+class FacebookAuthContext(ConsumerTemplateContext):
+    mode = 'BIGICON'
+    type = 'CUSTOM'
+    weight = 100
+    human_name = 'Facebook'
+    code_template = 'modules/facebookauth/button.html'
+    extra_css = []
+
+    API_KEY = settings.FB_API_KEY