Commits

ronald martinez committed d4a52e8

ok

  • Participants
  • Parent commits 826b1aa
  • Branches dev2

Comments (0)

Files changed (4)

controllers/__init__.py

 import logging
 import urllib
 import simplejson
+import hmac
+import base64
+import hashlib
+import datetime
 
 from models import User
 from tornado.web import RequestHandler
 )
 
 
+def get_age(date_of_birth):
+
+    logging.info('date_of_birth: %s' % date_of_birth)
+    tmp = None
+
+    try:
+
+        date_of_birth = datetime.datetime.strptime(
+            date_of_birth, '%d/%m/%Y').date()
+
+        if date_of_birth > datetime.date.today().replace(
+                year=date_of_birth.year):
+            tmp = datetime.date.today().year - date_of_birth.year - 1
+        else:
+            tmp = datetime.date.today().year - date_of_birth.year
+
+    except Exception as exc:
+        logging.error(exc)
+
+    return tmp
+
+
+def base64_url_decode(inp):
+
+    padding_factor = (4 - len(inp) % 4) % 4
+    inp += "=" * padding_factor
+
+    return base64.b64decode(unicode(inp).translate(
+        dict(zip(map(ord, u'-_'), u'+/'))))
+
+
 class BaseHandler(RequestHandler):
 
     def __init__(self, *args, **kwargs):
 
 class Facebook(object):
 
+    def window_location(redirect):
+
+        url = '%s%s' % (
+            settings.FACEBOOK_CANVAS_PAGE,
+            redirect
+        )
+
+        return "<script>window.top.location='%s'</script>" % url
+
+    def window_authorize_location(redirect=None):
+
+        url = '%s%s%s' % (
+            settings.FACEBOOK_CANVAS_PAGE,
+            'authorize/',
+            redirect
+        )
+        return "<script>window.top.location='%s'</script>" % url
+
+    def authorize_permission(redirect):
+
+        permissions = (
+            'email',
+            'friends_likes',
+            'friends_activities',
+            'friends_interests',
+            'friends_birthday',
+            'read_stream',
+            'user_birthday'
+        )
+
+        params = dict(
+            client_id=settings.FACEBOOK_API_KEY,
+            redirect_uri='%sauthorize/%s' % (
+                settings.FACEBOOK_CANVAS_PAGE, redirect),
+            scope=','.join(permissions)
+        )
+
+        url = '%s?%s' % (settings.FACEBOOK_OAUTH, urllib.urlencode(params))
+        return "<script>window.top.location='%s'</script>" % url
+
+    def parse_signed_request(self, signed_request, secret):
+
+        l = signed_request .split('.', 2)
+        encoded_sig = l[0]
+        payload = l[1]
+
+        sig = base64_url_decode(encoded_sig)
+        data = simplejson.loads(base64_url_decode(payload))
+
+        if data.get('algorithm').upper() != 'HMAC-SHA256':
+            logging.error('Unknown algorithm')
+            return None
+        else:
+            expected_sig = hmac.new(
+                secret, msg=payload, digestmod=hashlib.sha256
+            ).digest()
+
+        if sig != expected_sig:
+            return None
+        else:
+            return data
+
     def get_info(self, access_token, user_id):
 
         params = dict(

controllers/gift.py

 from tornado.web import authenticated
 
 from sqlalchemy.sql import and_, between
-from controllers import BaseHandler, Memcached, Session, Facebook
-from controllers.user import window_authorize_location, get_age
+from controllers import BaseHandler, Memcached, Session, Facebook, get_age
 
 facebook = Facebook()
 
 
                 if 'error' in data:
                     if data.get('error').get('type') == 'OAuthException':
-                        self.finish(window_authorize_location('friends'))
+
+                        self.finish(
+                            facebook.window_authorize_location('friends'))
 
                 else:
 
         gifts = []
         user = self.current_user
 
+        #print user.access_token
+
         for x in user.gifts:
 
             friend_data = facebook.get_info(x.friend_id, user.access_token)
 
-            gifts.append({x.friend_id: x.gift})
-
-            data[x.friend_id] = dict(
-                friend=dict(
-                    id=friend_data.get('id'),
-                    name=friend_data.get('name'),
-                    image='%s%s/picture?type=large' % (
-                        settings.FACEBOOK_GRAPH,
-                        x.friend_id)
-                ),
-                gifts=[y.values()[0] for y in gifts if x.friend_id in y]
-            )
+            if 'error' in friend_data:
+                #logging.info(friend_data.get('error'))
+                self.finish(
+                    facebook.window_authorize_location('list_friends'))
+            else:
+
+                gifts.append({x.friend_id: x.gift})
+
+                data[x.friend_id] = dict(
+                    friend=dict(
+                        id=friend_data.get('id'),
+                        name=friend_data.get('name'),
+                        image='%s%s/picture?type=large' % (
+                            settings.FACEBOOK_GRAPH,
+                            x.friend_id)
+                    ),
+                    gifts=[y.values()[0] for y in gifts if x.friend_id in y]
+                )
 
         self.render('list.html', data=data.values())
 

controllers/user.py

-import hmac
-import urllib
-import base64
-import hashlib
 import logging
 import settings
-import simplejson
 import cPickle
-import datetime
 
 from models import User
 
-from controllers import Session, BaseHandler, Facebook
+from controllers import Session, BaseHandler, Facebook, get_age
 from tornado.web import HTTPError, authenticated
 
 
 facebook = Facebook()
 
 
-def window_location(redirect):
-
-    url = '%s%s' % (settings.FACEBOOK_CANVAS_PAGE, redirect)
-    return "<script>window.top.location='%s'</script>" % url
-
-
-def window_authorize_location(redirect=None):
-
-    url = '%s%s%s' % (settings.FACEBOOK_CANVAS_PAGE, 'authorize/', redirect)
-    return "<script>window.top.location='%s'</script>" % url
-
-
-def authorize_permission(redirect):
-
-    permissions = (
-        'email',
-        'friends_likes',
-        'friends_activities',
-        'friends_interests',
-        'friends_birthday',
-        'read_stream',
-        'user_birthday'
-    )
-
-    params = dict(
-        client_id=settings.FACEBOOK_API_KEY,
-        redirect_uri='%sauthorize/%s' % (
-            settings.FACEBOOK_CANVAS_PAGE, redirect),
-        scope=','.join(permissions)
-    )
-
-    url = '%s?%s' % (settings.FACEBOOK_OAUTH, urllib.urlencode(params))
-    return "<script>window.top.location='%s'</script>" % url
-
-
-def get_age(date_of_birth):
-
-    logging.info('date_of_birth: %s' % date_of_birth)
-    tmp = None
-
-    try:
-
-        date_of_birth = datetime.datetime.strptime(
-            date_of_birth, '%d/%m/%Y').date()
-
-        if date_of_birth > datetime.date.today().replace(
-                year=date_of_birth.year):
-            tmp = datetime.date.today().year - date_of_birth.year - 1
-        else:
-            tmp = datetime.date.today().year - date_of_birth.year
-
-    except Exception as exc:
-        logging.error(exc)
-
-    return tmp
-
-
-def base64_url_decode(inp):
-
-    padding_factor = (4 - len(inp) % 4) % 4
-    inp += "=" * padding_factor
-
-    return base64.b64decode(unicode(inp).translate(
-        dict(zip(map(ord, u'-_'), u'+/'))))
-
-
-def parse_signed_request(signed_request, secret):
-
-    l = signed_request .split('.', 2)
-    encoded_sig = l[0]
-    payload = l[1]
-
-    sig = base64_url_decode(encoded_sig)
-    data = simplejson.loads(base64_url_decode(payload))
-
-    if data.get('algorithm').upper() != 'HMAC-SHA256':
-        logging.error('Unknown algorithm')
-        return None
-    else:
-        expected_sig = hmac.new(
-            secret, msg=payload, digestmod=hashlib.sha256
-        ).digest()
-
-    if sig != expected_sig:
-        return None
-    else:
-        return data
-
-
 class Authorize(BaseHandler):
 
     def check_xsrf_cookie(self):
 
     def post(self, redirect):
 
-        signed_request = self.get_argument('signed_request', None)
-
-        user_data_facebook = parse_signed_request(
-            signed_request,
+        user_data_facebook = facebook.parse_signed_request(
+            self.get_argument('signed_request', None),
             settings.FACEBOOK_API_SECRET
         )
 
         if not 'user_id' in user_data_facebook:
-            self.finish(authorize_permission(redirect))
+            self.finish(facebook.authorize_permission(redirect))
         else:
 
             user_data = {
 
         cookie = self.get_current_user()
 
+        logging.info('cookie: %s' % cookie)
+
         if not cookie:
-            self.finish(window_authorize_location('list_friends'))
+            self.finish(facebook.window_authorize_location('list_friends'))
         else:
             self.redirect(self.reverse_url('list_friends'))
 
 
         if 'error' in data:
             if data.get('error').get('type') == 'OAuthException':
-                self.finish(window_authorize_location('list_friends'))
+                self.finish(facebook.window_authorize_location('list_friends'))
             else:
                 raise HTTPError(500)
         else:
             for x in data.get('data'):
                 data_send.append(dict(id=x.get('id'),
                         image='%s/%s/picture?type=large' % (
-                            'https://graph.facebook.com/', x.get('id')),
+                            settings.FACEBOOK_GRAPH, x.get('id')),
                         name=x.get('name'),
                         exists=(x.get('id') in ids_friends))
                     )
     email = Column(Unicode(50), unique=True, nullable=False)
     fbid = Column(Unicode(100), unique=True, nullable=False)
     created_at = Column(DateTime, default=datetime.now)
-    access_token = Column(Unicode(200), nullable=False)
+    access_token = Column(Unicode(500), nullable=False)
     age = Column(Integer, nullable=True)
     gender = Column(Unicode(10), nullable=True)
     gifts = relationship('UserGift', backref='user')