# Path: yithlibraryserver/compat.py
# PY3 = sys.version_info[0] == 3
#     def encode_header(obj):  # pragma: no cover
#     def encode_header(obj):  # pragma: no cover
# 
# Path: yithlibraryserver/twitter/authorization.py
# def auth_header(method, url, original_params, settings, oauth_token='',
#                 nonce_=None, timestamp_=None):
#     params = list(original_params) + [
#         ('oauth_consumer_key', settings['twitter_consumer_key']),
#         ('oauth_nonce', nonce_ or nonce()),
#         ('oauth_signature_method', 'HMAC-SHA1'),
#         ('oauth_timestamp', str(timestamp_ or timestamp())),
#         ('oauth_version', '1.0'),
#         ]
#     params = [(quote(key), quote(value)) for key, value in params]
# 
#     signature = sign(method, url, params,
#                      settings['twitter_consumer_secret'], oauth_token)
#     params.append(('oauth_signature', signature))
# 
#     header = ", ".join(['%s="%s"' % (key, value) for key, value in params])
# 
#     return 'OAuth %s' % header
# 
# Path: yithlibraryserver/twitter/information.py
# def get_user_info(settings, user_id, oauth_token):
#     user_info_url = settings['twitter_user_info_url']
# 
#     params = (
#         ('oauth_token', oauth_token),
#         )
# 
#     auth = auth_header('GET', user_info_url, params, settings, oauth_token)
# 
#     response = requests.get(
#         user_info_url + '?' + url_encode({'user_id': user_id}),
#         headers={'Authorization': auth},
#         )
# 
#     if response.status_code != 200:
#         raise HTTPUnauthorized(response.text)
# 
#     return response.json()
# 
# Path: yithlibraryserver/user/utils.py
# def split_name(name):
#     parts = name.split(' ')
#     if len(parts) > 1:
#         first_name = parts[0]
#         last_name = ' '.join(parts[1:])
#     else:
#         first_name = parts[0]
#         last_name = ''
# 
#     return first_name, last_name
# 
# def register_or_update(request, provider, user_id, info, default_url='/'):
#     provider_key = get_provider_key(provider)
#     user = user_from_provider_id(request.db, provider, user_id)
#     if user is None:
# 
#         new_info = {'provider': provider, provider_key: user_id}
#         for attribute in ('screen_name', 'first_name', 'last_name', 'email'):
#             if attribute in info:
#                 new_info[attribute] = info[attribute]
#             else:
#                 new_info[attribute] = ''
# 
#         request.session['user_info'] = new_info
#         if 'next_url' not in request.session:
#             request.session['next_url'] = default_url
#         return HTTPFound(location=request.route_path('register_new_user'))
#     else:
#         changes = {'last_login': request.datetime_service.utcnow()}
# 
#         ga = request.google_analytics
#         if ga.is_in_session():
#             if not ga.is_stored_in_user(user):
#                 changes.update(ga.get_user_attr(ga.show_in_session()))
#             ga.clean_session()
# 
#         update_user(request.db, user, info, changes)
# 
#         if 'next_url' in request.session:
#             next_url = request.session['next_url']
#             del request.session['next_url']
#         else:
#             next_url = default_url
# 
#         request.session['current_provider'] = provider
#         remember_headers = remember(request, str(user['_id']))
#         return HTTPFound(location=next_url, headers=remember_headers)
# 
# Path: yithlibraryserver/user/utils.py
# def user_from_provider_id(db, provider, user_id):
#     provider_key = get_provider_key(provider)
#     return db.users.find_one({provider_key: user_id})


from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPUnauthorized
from yithlibraryserver.compat import urlparse
from yithlibraryserver.twitter.authorization import auth_header
from yithlibraryserver.twitter.information import get_user_info
from yithlibraryserver.user.utils import split_name, register_or_update
from yithlibraryserver.user.utils import user_from_provider_id
import requests

def twitter_callback(request):
    settings = request.registry.settings

    try:
        oauth_token = request.params['oauth_token']
    except KeyError:
        return HTTPBadRequest('Missing required oauth_token')

    try:
        oauth_verifier = request.params['oauth_verifier']
    except KeyError:
        return HTTPBadRequest('Missing required oauth_verifier')

    try:
        saved_oauth_token = request.session['oauth_token']
    except KeyError:
        return HTTPBadRequest('No oauth_token was found in the session')

    if saved_oauth_token != oauth_token:
        return HTTPUnauthorized("OAuth tokens don't match")
    else:
        del request.session['oauth_token']

    access_token_url = settings['twitter_access_token_url']

    params = (
        ('oauth_token', oauth_token),
        )


# Path: yithlibraryserver/compat.py
# PY3 = sys.version_info[0] == 3
#     def encode_header(obj):  # pragma: no cover
#     def encode_header(obj):  # pragma: no cover
# 
# Path: yithlibraryserver/twitter/authorization.py
# def auth_header(method, url, original_params, settings, oauth_token='',
#                 nonce_=None, timestamp_=None):
#     params = list(original_params) + [
#         ('oauth_consumer_key', settings['twitter_consumer_key']),
#         ('oauth_nonce', nonce_ or nonce()),
#         ('oauth_signature_method', 'HMAC-SHA1'),
#         ('oauth_timestamp', str(timestamp_ or timestamp())),
#         ('oauth_version', '1.0'),
#         ]
#     params = [(quote(key), quote(value)) for key, value in params]
# 
#     signature = sign(method, url, params,
#                      settings['twitter_consumer_secret'], oauth_token)
#     params.append(('oauth_signature', signature))
# 
#     header = ", ".join(['%s="%s"' % (key, value) for key, value in params])
# 
#     return 'OAuth %s' % header
# 
# Path: yithlibraryserver/twitter/information.py
# def get_user_info(settings, user_id, oauth_token):
#     user_info_url = settings['twitter_user_info_url']
# 
#     params = (
#         ('oauth_token', oauth_token),
#         )
# 
#     auth = auth_header('GET', user_info_url, params, settings, oauth_token)
# 
#     response = requests.get(
#         user_info_url + '?' + url_encode({'user_id': user_id}),
#         headers={'Authorization': auth},
#         )
# 
#     if response.status_code != 200:
#         raise HTTPUnauthorized(response.text)
# 
#     return response.json()
# 
# Path: yithlibraryserver/user/utils.py
# def split_name(name):
#     parts = name.split(' ')
#     if len(parts) > 1:
#         first_name = parts[0]
#         last_name = ' '.join(parts[1:])
#     else:
#         first_name = parts[0]
#         last_name = ''
# 
#     return first_name, last_name
# 
# def register_or_update(request, provider, user_id, info, default_url='/'):
#     provider_key = get_provider_key(provider)
#     user = user_from_provider_id(request.db, provider, user_id)
#     if user is None:
# 
#         new_info = {'provider': provider, provider_key: user_id}
#         for attribute in ('screen_name', 'first_name', 'last_name', 'email'):
#             if attribute in info:
#                 new_info[attribute] = info[attribute]
#             else:
#                 new_info[attribute] = ''
# 
#         request.session['user_info'] = new_info
#         if 'next_url' not in request.session:
#             request.session['next_url'] = default_url
#         return HTTPFound(location=request.route_path('register_new_user'))
#     else:
#         changes = {'last_login': request.datetime_service.utcnow()}
# 
#         ga = request.google_analytics
#         if ga.is_in_session():
#             if not ga.is_stored_in_user(user):
#                 changes.update(ga.get_user_attr(ga.show_in_session()))
#             ga.clean_session()
# 
#         update_user(request.db, user, info, changes)
# 
#         if 'next_url' in request.session:
#             next_url = request.session['next_url']
#             del request.session['next_url']
#         else:
#             next_url = default_url
# 
#         request.session['current_provider'] = provider
#         remember_headers = remember(request, str(user['_id']))
#         return HTTPFound(location=next_url, headers=remember_headers)
# 
# Path: yithlibraryserver/user/utils.py
# def user_from_provider_id(db, provider, user_id):
#     provider_key = get_provider_key(provider)
#     return db.users.find_one({provider_key: user_id})


# Path: yithlibraryserver/twitter/views.py
from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPUnauthorized
from yithlibraryserver.compat import urlparse
from yithlibraryserver.twitter.authorization import auth_header
from yithlibraryserver.twitter.information import get_user_info
from yithlibraryserver.user.utils import split_name, register_or_update
from yithlibraryserver.user.utils import user_from_provider_id
import requests


def twitter_callback(request):
    settings = request.registry.settings

    try:
        oauth_token = request.params['oauth_token']
    except KeyError:
        return HTTPBadRequest('Missing required oauth_token')

    try:
        oauth_verifier = request.params['oauth_verifier']
    except KeyError:
        return HTTPBadRequest('Missing required oauth_verifier')

    try:
        saved_oauth_token = request.session['oauth_token']
    except KeyError:
        return HTTPBadRequest('No oauth_token was found in the session')

    if saved_oauth_token != oauth_token:
        return HTTPUnauthorized("OAuth tokens don't match")
    else:
        del request.session['oauth_token']

    access_token_url = settings['twitter_access_token_url']

    params = (
        ('oauth_token', oauth_token),
        )


    auth = auth_header('POST', access_token_url, params, settings, oauth_token)