Commits

ronald martinez  committed 614f0ce

ok

  • Participants
  • Parent commits ac8fe73
  • Branches dev2

Comments (0)

Files changed (4)

File controllers/__init__.py

     def __init__(self, *args, **kwargs):
         super(BaseHandler, self).__init__(*args, **kwargs)
 
+    @property
+    def user_data_facebook(self):
+
+        if not hasattr(self, '_user_data_facebook'):
+
+            cookie = self.get_secure_cookie('user')
+
+            if not cookie:
+                return None
+            else:
+                self._user_data_facebook = cPickle.loads(cookie)
+
+        return self._user_data_facebook
+
     def get_current_user(self):
 
-        user = None
         cookie = self.get_secure_cookie('user')
-        cookie_user = cPickle.loads(cookie) if cookie else None
 
-        if cookie_user:
+        if not cookie:
+            return None
+        else:
+
+            cookie_user = cPickle.loads(cookie)
 
             user = Session.query(User).filter_by(
                 fbid=cookie_user.get('user_id')).first()
 
-        user.access_token = cookie_user.get('access_token')
-        return user
+            if user:
+                return cookie_user.get('access_token')
+            else:
+                return None
 
     def render_string(self, template, **kwargs):
 

File controllers/gift.py

     def get(self, friend_id, **kwargs):
 
         user = self.current_user
-
         skus = Memcached.get(str(friend_id))
 
         if not skus:

File controllers/user.py

     def check_xsrf_cookie(self):
         pass
 
-    def _update_user(self):
+    def post(self, redirect):
 
-        cookie = self.get_secure_cookie('user')
-        user_data_facebook = cPickle.loads(cookie) if cookie else None
+        signed_request = self.get_argument('signed_request', None)
 
-        if not user_data_facebook:
-            raise HTTPError(500)
+        user_data_facebook = parse_signed_request(
+            signed_request,
+            settings.FACEBOOK_API_SECRET
+        )
 
-        user = Session.query(User).filter_by(
-            fbid=user_data_facebook.get('user_id'))
+        if not 'user_id' in user_data_facebook:
+            self.finish(authorize_permission(redirect))
+        else:
 
-        if not user.first():
+            data = cPickle.dumps({
+                'user_id': user_data_facebook['user_id'],
+                'access_token': user_data_facebook['oauth_token'],
+            }, -1)
 
-            params = dict(
-                access_token=user_data_facebook.get('access_token'),
-                fields='email,birthday,gender,name'
-            )
+            self.set_secure_cookie('user', data)
 
-            url = '%s?%s' % (
-                '%s/%s' % (
-                    settings.FACEBOOK_GRAPH,
-                    user_data_facebook.get('user_id')
-                ),
-                 urllib.urlencode(params)
+            self.check_user(
+                data=user_data_facebook,
+                wait_seconds=2
             )
 
-            http_client = AsyncHTTPClient()
-            http_client.fetch(url, self.add_user)
+            print "redirect", redirect
+            self.redirect(self.reverse_url(redirect))
 
-    def add_user(self, user_data_facebook_graph):
-
-        if user_data_facebook_graph.error:
-            raise HTTPError(500)
-        else:
+    def check_user(self, data, wait_seconds):
 
-            user_data_facebook_graph = simplejson.loads(
-                user_data_facebook_graph.body)
-
-            cookie = self.get_secure_cookie('user')
-            cookie_user = cPickle.loads(cookie) if cookie else None
-
-            if not cookie_user:
-                raise HTTPError(500)
+        def callback():
+            user = Session.query(User).filter_by(
+                fbid=data.get('user_id'))
 
-            user = User()
-            user.name = user_data_facebook_graph.get('name')
-            user.fbid = cookie_user.get('user_id')
-            user.email = user_data_facebook_graph.get('email')
-            user.access_token = cookie_user.get('access_token')
-
-            if 'gender' in user_data_facebook_graph:
-                user.gender = user_data_facebook_graph.get('gender')
-
-            if 'birthday' in user_data_facebook_graph:
+            if not user.first():
+                self.add_user(data)
+            else:
+                logging.info('exists user')
 
-                user_age = get_age(
-                    user_data_facebook_graph.get('birthday'))
+        IOLoop.instance().add_timeout(time.time() + wait_seconds, callback)
 
-                if user_age:
-                    user.age = user_age
+    def add_user(self, user_data_facebook):
 
-            Session.add(user)
+        def callback(user_data_facebook_graph):
 
-            try:
-                Session.commit()
-            except Exception as exc:
-                logging.error(exc)
+            if user_data_facebook_graph.error:
+                raise HTTPError(500)
             else:
-                logging.info('save user')
 
-        self.finish()
+                user_data_facebook_graph = simplejson.loads(
+                    user_data_facebook_graph.body)
 
-    def post(self, redirect):
+                user = User()
+                user.name = user_data_facebook_graph.get('name')
+                user.fbid = user_data_facebook.get('user_id')
+                user.email = user_data_facebook_graph.get('email')
+                user.access_token = user_data_facebook.get('access_token')
 
-        signed_request = self.get_argument('signed_request', None)
+                if 'gender' in user_data_facebook_graph:
+                    user.gender = user_data_facebook_graph.get('gender')
 
-        if not signed_request:
-            raise HTTPError(500)
+                if 'birthday' in user_data_facebook_graph:
 
-        user_data_facebook = parse_signed_request(
-            signed_request,
-            settings.FACEBOOK_API_SECRET
-        )
+                    user_age = get_age(
+                        user_data_facebook_graph.get('birthday'))
 
-        if not 'user_id' in user_data_facebook:
-            self.finish(authorize_permission(redirect))
-        else:
+                    if user_age:
+                        user.age = user_age
 
-            data = cPickle.dumps({
-                'user_id': user_data_facebook['user_id'],
-                'access_token': user_data_facebook['oauth_token'],
-                'expires': user_data_facebook['expires']
-            }, -1)
+                Session.add(user)
 
-            self.set_secure_cookie('user', data)
+                try:
+                    Session.commit()
+                except Exception as exc:
+                    logging.error(exc)
+                else:
+                    logging.info('save user')
 
-            IOLoop.instance().add_timeout(
-                time.time() + 2,
-                self._update_user
-            )
+        params = dict(
+            access_token=user_data_facebook.get('oauth_token'),
+            fields='email,birthday,gender,name'
+        )
 
-            if redirect == 'index':
-                redirect = ''
+        url = '%s?%s' % (
+            '%s/%s' % (
+                settings.FACEBOOK_GRAPH,
+                user_data_facebook.get('user_id')
+            ),
+             urllib.urlencode(params)
+        )
 
-            self.finish(window_location(redirect))
+        http_client = AsyncHTTPClient()
+        http_client.fetch(url, callback)
 
 
 class Index(BaseHandler):
     def check_xsrf_cookie(self):
         pass
 
-    @asynchronous
     def post(self):
 
-        cookie = self.get_secure_cookie('user')
+        cookie = self.get_current_user()
 
         if not cookie:
-            self.finish(window_authorize_location('index'))
+            self.finish(window_authorize_location('list_friends'))
         else:
-            user_data_facebook = cPickle.loads(cookie) if cookie else None
-
-            print user_data_facebook
-
-            self.finish(window_location('friends'))
+            self.redirect(self.reverse_url('list_friends'))
 
 
 class ListFriends(BaseHandler):
     def check_xsrf_cookie(self):
         pass
 
-    def post(self):
-
-        cookie = self.get_secure_cookie('user')
-        cookie_user = cPickle.loads(cookie) if cookie else None
-
-        if not cookie_user:
-            raise HTTPError(500)
+    def get(self):
 
         limit, offset = self.pagination(
             settings.PAGES_LIMIT,
             self.get_argument('page', '1')
         )
 
-        at = cookie_user.get('access_token')
-
         params = dict(
-            access_token=at,
+            access_token=self.user_data_facebook.get('oauth_token'),
             fields='name',
             limit=limit,
             offset=offset
         )
 
         if 'error' in data:
-
             if data.get('error').get('type') == 'OAuthException':
                 self.finish(window_authorize_location('friends'))
             else:
                 raise HTTPError(500)
-
-        self.render('index.html', data=data.get('data'))
+        else:
+            self.render('index.html', data=data.get('data'))
     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(200), nullable=False)
     age = Column(Integer, nullable=True)
     gender = Column(Unicode(10), nullable=True)
     gifts = relationship('UserGift', backref='user')