<commit_before># -*- coding: utf-8 -*-

from urllib import urlencode, quote
from urllib2 import urlopen, URLError
from urlparse import parse_qs

from flask import request, session, redirect, flash, url_for, json
from flask.ext.oauth import OAuth, OAuthException  # OAuth 1.0a

from lastuserapp import app
from lastuserapp.models import db, UserExternalId, UserEmail, User
from lastuserapp.views import get_next_url, login_internal, register_internal
from lastuserapp.utils import valid_username, get_gravatar_md5sum

# OAuth 1.0a handlers
oauth = OAuth()
twitter = oauth.remote_app('twitter',
    base_url='https://api.twitter.com/1/',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authenticate',
    consumer_key=app.config.get('OAUTH_TWITTER_KEY'),
    consumer_secret=app.config.get('OAUTH_TWITTER_SECRET'),
)


def get_extid_token(service):
    useridinfo = session.get('userid_external')
    if useridinfo:
        if service != useridinfo.get('service'):
            return None
        extid = UserExternalId.query.filter_by(service=service, userid=useridinfo['userid']).first()
        if extid:
            return {'oauth_token': extid.oauth_token,
                    'oauth_token_secret': extid.oauth_token_secret}
    return None


@twitter.tokengetter
def get_twitter_token():
    return get_extid_token('twitter')


@app.route('/login/twitter')
def login_twitter():
    next_url = get_next_url(referrer=False)
    try:
        return twitter.authorize(callback=url_for('login_twitter_authorized',
            next=next_url))
    except OAuthException, e:
        flash("Twitter login failed: %s" % unicode(e), category="error")
        return redirect(next_url)


@app.route('/login/twitter/callback')
@twitter.authorized_handler
def login_twitter_authorized(resp):
    next_url = get_next_url()
    if resp is None:
        flash(u'You denied the request to login via Twitter.')
        return redirect(next_url)

    # Try to read more from the user's Twitter profile
    try:
        twinfo = json.loads(urlopen('http://api.twitter.com/1/users/lookup.json?%s' % urlencode({'user_id': resp['user_id']})).read())[0]
        return_url = config_external_id(service='twitter',
                                        service_name='Twitter',
                                        user=None,
                                        userid=resp['user_id'],
                                        username=resp['screen_name'],
                                        fullname=twinfo.get('name', '@' + resp['screen_name']),
                                        avatar=twinfo.get('profile_image_url').replace("normal.", "bigger."),
                                        access_token=resp['oauth_token'],
                                        secret=resp['oauth_token_secret'],
                                        token_type=None,<commit_msg>Twitter login error handler.<commit_after># -*- coding: utf-8 -*-

from functools import wraps

from urllib import urlencode, quote
from urllib2 import urlopen, URLError
from urlparse import parse_qs

from flask import request, session, redirect, flash, url_for, json
from flask.ext.oauth import OAuth, OAuthException  # OAuth 1.0a

from lastuserapp import app
from lastuserapp.models import db, UserExternalId, UserEmail, User
from lastuserapp.views import get_next_url, login_internal, register_internal
from lastuserapp.utils import valid_username, get_gravatar_md5sum

# OAuth 1.0a handlers
oauth = OAuth()
twitter = oauth.remote_app('twitter',
    base_url='https://api.twitter.com/1/',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authenticate',
    consumer_key=app.config.get('OAUTH_TWITTER_KEY'),
    consumer_secret=app.config.get('OAUTH_TWITTER_SECRET'),
)


def get_extid_token(service):
    useridinfo = session.get('userid_external')
    if useridinfo:
        if service != useridinfo.get('service'):
            return None
        extid = UserExternalId.query.filter_by(service=service, userid=useridinfo['userid']).first()
        if extid:
            return {'oauth_token': extid.oauth_token,
                    'oauth_token_secret': extid.oauth_token_secret}
    return None


@twitter.tokengetter
def get_twitter_token():
    return get_extid_token('twitter')


@app.route('/login/twitter')
def login_twitter():
    next_url = get_next_url(referrer=False)
    try:
        return twitter.authorize(callback=url_for('login_twitter_authorized',
            next=next_url))
    except OAuthException, e:
        flash("Twitter login failed: %s" % unicode(e), category="error")
        return redirect(url_for('login'))


def twitter_exception_handler(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except OAuthException, e:
            flash("Twitter login failed: %s" % unicode(e), category="error")
            return redirect(url_for('login'))
    return decorated_function


@app.route('/login/twitter/callback')
@twitter_exception_handler
@twitter.authorized_handler
def login_twitter_authorized(resp):
    next_url = get_next_url()
    if resp is None:
        flash(u'You denied the request to login via Twitter.')
        return redirect(next_url)

    # Try to read more from the user's Twitter profile
    try:
        twinfo = json.loads(urlopen('http://api.twitter.com/1/users/lookup.json?%s' % urlencode({'user_id': resp['user_id']})).read())[0]
        return_url = config_external_id(service='twitter',
                                        service_name='Twitter',
                                        user=None,
                                        userid=resp['user_id'],
                                        username=resp['screen_name'],
                                        fullname=twinfo.get('name', '@' + resp['screen_name']),
                                        avatar=twinfo.get('profile_image_url').replace("normal.", "bigger."),
                                        access_token=resp['oauth_token'],
                                        secret=resp['oauth_token_secret'],
                                        token_type=None,
{'fraction_non_alphanumeric': 0.11241035235422513, 'fraction_numerical': 0.0031181789834736516, 'mean_word_length': 2.6304470854555744, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 8, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2247590', 'n_tokens_mistral': 1848, 'n_tokens_neox': 1802, 'n_words': 356}