]> git.openstreetmap.org Git - osqa.git/commitdiff
do not use the JavaScript SDK for Facebook authentication, use the server side flow...
authorjordan <jordan@0cfe37f9-358a-4d5e-be75-b63607b5c754>
Sat, 10 Dec 2011 11:21:03 +0000 (11:21 +0000)
committerjordan <jordan@0cfe37f9-358a-4d5e-be75-b63607b5c754>
Sat, 10 Dec 2011 11:21:03 +0000 (11:21 +0000)
git-svn-id: http://svn.osqa.net/svnroot/osqa/trunk@1211 0cfe37f9-358a-4d5e-be75-b63607b5c754

forum/views/auth.py
forum_modules/facebookauth/authentication.py
forum_modules/facebookauth/settings.py
forum_modules/facebookauth/templates/button.html

index d11c20bb417cb62163987aa38d7f0d1bf33088ca..9e7d6c6f828e92d43d76a79dfe90a18e712911d8 100644 (file)
@@ -196,11 +196,7 @@ def external_register(request):
 
         provider_class = AUTH_PROVIDERS[auth_provider].consumer
 
 
         provider_class = AUTH_PROVIDERS[auth_provider].consumer
 
-        # Pass the cookies to the Facebook authentication class get_user_data method. We need them to take the access token.
-        if provider_class.__class__.__name__ == 'FacebookAuthConsumer':
-            user_data = provider_class.get_user_data(request.COOKIES)
-        else:
-            user_data = provider_class.get_user_data(request.session['assoc_key'])
+        user_data = provider_class.get_user_data(request.session['assoc_key'])
 
         if not user_data:
             user_data = request.session.get('auth_consumer_data', {})
 
         if not user_data:
             user_data = request.session.get('auth_consumer_data', {})
index 4e9a44ac3255db9086393cf037806a9278bcd10a..55cf16d88b4d986de0169b96b0be8d4a861fa2a4 100644 (file)
@@ -1,17 +1,20 @@
-import hashlib
-from time import time
-from datetime import datetime
+# -*- coding: utf-8 -*-
+
+import cgi
+import logging
+
 from urllib import urlopen,  urlencode
 from urllib import urlopen,  urlencode
-from urlparse import parse_qs
 from forum.authentication.base import AuthenticationConsumer, ConsumerTemplateContext, InvalidAuthentication
 from forum.authentication.base import AuthenticationConsumer, ConsumerTemplateContext, InvalidAuthentication
-from django.utils.translation import ugettext as _
+
+from django.conf import settings as django_settings
 from django.utils.encoding import smart_unicode
 from django.utils.encoding import smart_unicode
+from django.utils.translation import ugettext as _
 
 import settings
 
 try:
     from json import load as load_json
 
 import settings
 
 try:
     from json import load as load_json
-except:
+except Exception:
     from django.utils.simplejson import JSONDecoder
 
     def load_json(json):
     from django.utils.simplejson import JSONDecoder
 
     def load_json(json):
@@ -19,60 +22,54 @@ except:
         return decoder.decode(json.read())
 
 class FacebookAuthConsumer(AuthenticationConsumer):
         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):
     
     def process_authentication_request(self, request):
-        API_KEY = str(settings.FB_API_KEY)
-
-        # Check if the Facebook cookie has been received.
-        if 'fbs_%s' % API_KEY in request.COOKIES:
-            fbs_cookie = request.COOKIES['fbs_%s' % API_KEY]
-            parsed_fbs = parse_qs(smart_unicode(fbs_cookie))
-            self.parsed_fbs = parsed_fbs
-
-            # Check if the session hasn't expired.
-            if self.check_session_expiry(request.COOKIES):
-                return parsed_fbs['uid'][0]
-            else:
-                raise InvalidAuthentication(_('Sorry, your Facebook session has expired, please try again'))
-        else:
-            raise InvalidAuthentication(_('The authentication with Facebook connect failed, cannot find authentication tokens'))
-    def check_session_expiry(self, cookies):
-        return datetime.fromtimestamp(float(self.parsed_fbs['expires'][0])) > datetime.now()
-
-    def get_user_data(self, cookies):
-        API_KEY = str(settings.FB_API_KEY)
-        fbs_cookie = cookies['fbs_%s' % API_KEY]
-        parsed_fbs = parse_qs(smart_unicode(fbs_cookie))
-
-        # Communicate with the access token to the Facebook oauth interface.
-        json = load_json(urlopen('https://graph.facebook.com/me?access_token=%s' % parsed_fbs['access_token'][0]))
-
-        first_name = smart_unicode(json['first_name'])
-        last_name = smart_unicode(json['last_name'])
-        full_name = '%s %s' % (first_name, last_name)
-
-        # There is a limit in the Django user model for the username length (no more than 30 characaters)
-        if len(full_name) <= 30:
-            username = full_name
-        # If the full name is too long use only the first
-        elif len(first_name) <= 30:
-            username = first_name
-        # If it's also that long -- only the last
-        elif len(last_name) <= 30:
-            username = last_name
-        # If the real name of the user is indeed that weird, let him choose something on his own =)
-        else:
-            username = ''
+        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]
+
+            # Store the access token in cookie
+            request.session["assoc_key"] = access_token
+
+            return access_token
+        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, assoc_key):
+        profile = load_json(urlopen("https://graph.facebook.com/me?" + urlencode(dict(access_token=assoc_key))))
+
+        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.
 
         # 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(json['email'])
+        email = smart_unicode(profile['email'])
         if len(email) > 75:
             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 {
         # Return the user data.
         return {
-            'username': username,
+            'username': name,
             'email': email,
         }
 
             'email': email,
         }
 
@@ -84,4 +81,4 @@ class FacebookAuthContext(ConsumerTemplateContext):
     code_template = 'modules/facebookauth/button.html'
     extra_css = []
 
     code_template = 'modules/facebookauth/button.html'
     extra_css = []
 
-    API_KEY = settings.FB_API_KEY
\ No newline at end of file
+    API_KEY = settings.FB_API_KEY
index 7f34a210ccaebcc06cd3531fb5c69b21d4f1285f..4127e61c2c4f53dc7a30cb7d7cde12b503d1b066 100644 (file)
@@ -1,3 +1,5 @@
+# -*- coding: utf-8 -*-
+
 from forum.settings import EXT_KEYS_SET
 from forum.settings.base import Setting
 
 from forum.settings import EXT_KEYS_SET
 from forum.settings.base import Setting
 
index 403ef71b12e6b742e897be83e1af5c35f9b0a112..497533d056dfc894c2c42566aef5f05cc873a731 100644 (file)
@@ -1,31 +1,3 @@
 {% load extra_tags %}\r
 \r
 {% load extra_tags %}\r
 \r
-<div id="fb-root"></div>\r
-<script src="http://connect.facebook.net/en_US/all.js"></script>\r
-<script>\r
-    function check_login_status() {\r
-        var FB_API_KEY = "{{ provider.API_KEY }}";\r
-        FB.init({\r
-            appId:FB_API_KEY, cookie:true,\r
-            status:true, xfbml:true, oauth:true\r
-        });\r
-        FB.getLoginStatus(function(response) {\r
-            if (response.session) {\r
-                redirect_to_done_page();\r
-            } else {\r
-                FB.login(function(response) {\r
-                    if (response.session) {\r
-                      redirect_to_done_page();\r
-                    } else {\r
-                      // user cancelled login\r
-                    }\r
-                }, {perms:'email'});\r
-            }\r
-        });\r
-    }\r
-\r
-    function redirect_to_done_page() {\r
-        window.location = "{% url auth_provider_done provider=provider.id %}";\r
-    }\r
-</script>\r
-<a style="position: relative; top: -8px;" href="javascript:void(0);" onclick="check_login_status()" perms="email"><img src="{% media '/media/images/openid/facebook.gif' %}" /></a>\r
+<a style="position: relative; top: -8px;" href="{% url auth_provider_signin provider="facebook" %}"><img src="{% media '/media/images/openid/facebook.gif' %}" /></a>\r