Source

find-gift / controllers / user.py

Full commit
import hmac
import urllib
import base64
import hashlib
import logging
import settings
import simplejson
import cPickle
import datetime
import time

from models import User

from controllers import Session, BaseHandler
from tornado.web import HTTPError, asynchronous
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop


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):

    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):
        pass

    def post(self, redirect):

        #print "PPPP"

        signed_request = self.get_argument('signed_request', None)

        if not signed_request:
            raise HTTPError(500)

        user_data_facebook = parse_signed_request(
            signed_request,
            settings.FACEBOOK_API_SECRET
        )

        print user_data_facebook

        return

        if not 'user_id' in user_data_facebook:
            self.finish(authorize_permission(redirect))
        else:

            data = cPickle.dumps({
                'user_id': user_data_facebook['user_id'],
                'access_token': user_data_facebook['oauth_token'],
                'expires': user_data_facebook['expires']
            }, -1)

            self.set_secure_cookie('user', data)

            IOLoop.instance().add_timeout(
                time.time() + 2,
                self._update_user
            )

            if redirect=='index':
                redirect = ''

            self.finish(window_location(redirect))


class Index(BaseHandler):

    def check_xsrf_cookie(self):
        pass

    @asynchronous
    def post(self):

        cookie = self.get_secure_cookie('user')

        if not cookie:
            self.finish(window_authorize_location('index'))
        else:
            user_data_facebook = cPickle.loads(cookie) if cookie else None

            print user_data_facebook

            self.finish(window_location('friends'))

    def _update_user(self):

        cookie = self.get_secure_cookie('user')
        user_data_facebook = cPickle.loads(cookie) if cookie else None

        if not user_data_facebook:
            raise HTTPError(500)

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

        if not user.first():

            params = dict(
                access_token=user_data_facebook.get('access_token'),
                fields='email,birthday,gender,name'
            )

            url = '%s?%s' % (
                '%s/%s' % (
                    settings.FACEBOOK_GRAPH,
                    user_data_facebook.get('user_id')
                ),
                 urllib.urlencode(params)
            )

            http_client = AsyncHTTPClient()
            http_client.fetch(url, self.add_user)

        else:

            print "exists"
            """
            try:
                user.update({'access_token': user_data_facebook.get(
                    'access_token')})
            except Exception as exc:
                logging.error(exc)
            else:
                logging.info('update user token')
            """

    def add_user(self, user_data_facebook_graph):

        if user_data_facebook_graph.error:
            raise HTTPError(500)
        else:

            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)

            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:

                user_age = get_age(
                    user_data_facebook_graph.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')

        self.finish()


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)

        limit, offset = self.pagination(
            settings.PAGES_LIMIT,
            self.get_argument('page', '1')
        )

        at = 'AAAG1OBVnjW8BAEQP8V5bgKqwhZB1OU5ejqtxKhth8rQx9ZAgeEbauVZCe7rHEclfZBXfJMSPo3ZCqzFDWyzemLSlbCZCceAZC8FkQzLafW43gZDZD'
        #at = cookie_user.get('access_token')

        params = dict(
            access_token=at,
            fields='name',
            limit=limit,
            offset=offset
        )

        data = self.load_data_url(
            url='%s/me/friends' % settings.FACEBOOK_GRAPH,
            params=params,
            json=True
        )

        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'))