find-gift / 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 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):
        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:

            user_data = {
                'user_id': user_data_facebook['user_id'],
                'access_token': user_data_facebook['oauth_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:
                logging.info('exists 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()

        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

    @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:
            if data.get('error').get('type') == 'OAuthException':
                self.finish(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' % (
                            'https://graph.facebook.com/', 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.