find-gift / controllers / user.py

import logging
import settings
import cPickle
import hashlib
import random

from models import User

from controllers import Session, BaseHandler, Facebook, get_age
from tornado.web import HTTPError, authenticated


facebook = Facebook()


class Authorize(BaseHandler):

    def check_xsrf_cookie(self):
        pass

    def post(self, redirect):

        user_data_facebook = facebook.parse_signed_request(
            self.get_argument('signed_request', None),
            settings.FACEBOOK_API_SECRET
        )

        oauth_state = self.get_cookie('oauth_state')
        state = self.get_argument('state', None)
        code = self.get_argument('code', None)

        if not 'user_id' in user_data_facebook or not code:
            state = hashlib.md5(str(random.random())).hexdigest()
            self.set_cookie('oauth_state', state)
            self.finish(facebook.authorize_permission(redirect, state))
        else:
            if oauth_state != state:
                logging.error('attack')
            else:
                access_token = facebook.get_access_token_code(code, redirect)
                logging.info('access_token: %s' % access_token)

                user_data = {
                    'user_id': user_data_facebook['user_id'],
                    'access_token': access_token,
                }

                data = cPickle.dumps(user_data, -1)
                self.set_secure_cookie('user', data)

                user = Session.query(User).filter_by(
                    fbid=user_data_facebook.get('user_id'))

                if not user.first():
                    self.add_user(user_data)
                else:

                    try:
                        user.update({'access_token': access_token})
                        Session.commit()
                    except Exception as exc:
                        logging.error(exc)
                    else:
                        logging.info('update user')

                self.redirect(self.reverse_url(redirect))

    def add_user(self, session):

        data = facebook.get_info(
            session.get('access_token'),
            session.get('user_id')
        )

        if 'error' in data:
            logging.info(data.get('error'))
        else:

            user = User()
            user.name = data.get('name')
            user.fbid = session.get('user_id')
            user.email = data.get('email')
            user.access_token = session.get('access_token')

            if 'gender' in data:
                user.gender = data.get('gender')

            if 'birthday' in data:

                user_age = get_age(
                    data.get('birthday'))

                if user_age:
                    user.age = user_age

            Session.add(user)

            try:
                Session.commit()
            except Exception as exc:
                logging.error(exc)
            else:
                logging.info('save user')


class Index(BaseHandler):

    def check_xsrf_cookie(self):
        pass

    def post(self):

        cookie = self.get_current_user()
        logging.info('cookie: %s' % cookie)

        if not cookie:
            self.finish(facebook.window_authorize_location('list_friends'))
        else:
            self.redirect(self.reverse_url('list_friends'))


class ListFriends(BaseHandler):

    def check_xsrf_cookie(self):
        pass

    @authenticated
    def get(self):

        ids_friends = Session.query(User).filter_by(
            fbid=self.user_data_facebook.get('user_id')).first()

        if ids_friends:
            ids_friends = [x.friend_id for x in ids_friends.gifts]
        else:
            ids_friends = []

        data = facebook.get_friends(
            self.current_user.access_token,
            self.current_user.fbid,
            settings.PAGES_LIMIT,
            self.get_argument('page', '1')
        )

        if 'error' in data:
            logging.info(data.get('error').get('message'))
            if data.get('error').get('type') == 'OAuthException':
                # docs/reference/api/errors/
                self.finish(
                    facebook.window_authorize_location('list_friends'))
            else:
                raise HTTPError(500)
        else:

            data_send = []

            for x in data.get('data'):
                data_send.append(dict(id=x.get('id'),
                        image='%s/%s/picture?type=large' % (
                            settings.FACEBOOK_GRAPH, x.get('id')),
                        name=x.get('name'),
                        exists=(x.get('id') in ids_friends))
                    )

            self.render('index.html', data=data_send)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.