# Path: yithlibraryserver/user/utils.py
# 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/persona/audience.py
# def get_audience(public_url_root):
#     parts = urlparse.urlparse(public_url_root)
#     if parts.port is None:
#         if parts.scheme == 'http':
#             port = 80
#         elif parts.scheme == 'https':
#             port = 443
#         else:
#             raise ValueError('Error geting the port from %s' % public_url_root)
#     else:
#         port = parts.port
# 
#     return '%s://%s:%d' % (parts.scheme, parts.hostname, port)


import hashlib
import requests
from pyramid.httpexceptions import HTTPBadRequest, HTTPForbidden
from pyramid.httpexceptions import HTTPMethodNotAllowed, HTTPServerError
from yithlibraryserver.user.utils import register_or_update
from yithlibraryserver.persona.audience import get_audience
# along with Yith Library Server.  If not, see <http://www.gnu.org/licenses/>.






def persona_login(request):
    if request.method != 'POST':
        return HTTPMethodNotAllowed('Only POST is allowed')

    assertion = request.POST.get('assertion', None)
    if assertion is None:
        return HTTPBadRequest('The assertion parameter is required')

    if 'next_url' in request.params and request.params['next_url']:
        request.session['next_url'] = request.params['next_url']

    settings = request.registry.settings
    data = {'assertion': assertion,
            'audience': get_audience(settings['public_url_root'])}
    response = requests.post(settings['persona_verifier_url'],
                             data=data, verify=True)

    if response.ok:
        verification_data = response.json()
        if verification_data['status'] == 'okay':
            email = verification_data['email']
            info = {'email': email}
            user_id = hashlib.sha1(email.encode('utf-8')).hexdigest()

# Path: yithlibraryserver/user/utils.py
# 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/persona/audience.py
# def get_audience(public_url_root):
#     parts = urlparse.urlparse(public_url_root)
#     if parts.port is None:
#         if parts.scheme == 'http':
#             port = 80
#         elif parts.scheme == 'https':
#             port = 443
#         else:
#             raise ValueError('Error geting the port from %s' % public_url_root)
#     else:
#         port = parts.port
# 
#     return '%s://%s:%d' % (parts.scheme, parts.hostname, port)


# Path: yithlibraryserver/persona/views.py
import hashlib
import requests
from pyramid.httpexceptions import HTTPBadRequest, HTTPForbidden
from pyramid.httpexceptions import HTTPMethodNotAllowed, HTTPServerError
from yithlibraryserver.user.utils import register_or_update
from yithlibraryserver.persona.audience import get_audience

# along with Yith Library Server.  If not, see <http://www.gnu.org/licenses/>.






def persona_login(request):
    if request.method != 'POST':
        return HTTPMethodNotAllowed('Only POST is allowed')

    assertion = request.POST.get('assertion', None)
    if assertion is None:
        return HTTPBadRequest('The assertion parameter is required')

    if 'next_url' in request.params and request.params['next_url']:
        request.session['next_url'] = request.params['next_url']

    settings = request.registry.settings
    data = {'assertion': assertion,
            'audience': get_audience(settings['public_url_root'])}
    response = requests.post(settings['persona_verifier_url'],
                             data=data, verify=True)

    if response.ok:
        verification_data = response.json()
        if verification_data['status'] == 'okay':
            email = verification_data['email']
            info = {'email': email}
            user_id = hashlib.sha1(email.encode('utf-8')).hexdigest()

            return register_or_update(request, 'persona', user_id,