find-gift / controllers / user.py

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

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

        user_data_facebook = parse_signed_request(
            signed_request,
            settings.FACEBOOK_API_SECRET
        )

        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'],
            }, -1)

            self.set_secure_cookie('user', data)

            self.check_user(
                data=user_data_facebook,
                wait_seconds=2
            )

            self.redirect(self.reverse_url(redirect))

    def check_user(self, data):

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

        if not user.first():
            self.add_user(data)
        else:
            logging.info('exists user')

    @asynchronous
    def add_user(self, data):

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

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

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

    def on_user_save(self, user_data_facebook_graph):

        user_data_facebook = self.user_data_facebook

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

            user_data_facebook_graph = simplejson.loads(
                user_data_facebook_graph.body)

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

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

    """
    def check_user(self, data, wait_seconds):

        def callback():
            user = Session.query(User).filter_by(
                fbid=data.get('user_id'))

            if not user.first():
                self.add_user(data)
            else:
                logging.info('exists user')

        IOLoop.instance().add_timeout(time.time() + wait_seconds, callback)

    def add_user(self, user_data_facebook):

        def callback(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)

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

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

        params = dict(
            access_token=user_data_facebook.get('oauth_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, callback)
    """


class Index(BaseHandler):

    def check_xsrf_cookie(self):
        pass

    def post(self):

        cookie = self.get_current_user()

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


class ListFriends(BaseHandler):

    def check_xsrf_cookie(self):
        pass

    def get(self):

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

        params = dict(
            access_token=self.user_data_facebook.get('access_token'),
            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('list_friends'))
            else:
                raise HTTPError(500)
        else:
            self.render('index.html', data=data.get('data'))
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.