from django.utils.six.moves import urllib_parse
from django.utils.six.moves.urllib_request import urlopen, Request
import logging

logger = logging.getLogger(__name__)


def REMIE_verify_cas2(ticket, service):
    """Verifies CAS 2.0+ XML-based authentication ticket.
    Returns username on success and None on failure.
    """
    try:
        from xml.etree import ElementTree
    except ImportError:
        from elementtree import ElementTree

    params = [('ticket', ticket), ('service', service)]
    url = (urllib_parse.urljoin(settings.CAS_SERVER_URL, 'serviceValidate') + '?' +
           urllib_parse.urlencode(params))
    page = urlopen(url)
    try:
        response = page.read()
        logger.debug("Verify CAS response : ")
        logger.debug(response)
        tree = ElementTree.fromstring(response)
        if tree[0].tag.endswith('authenticationSuccess'):
            return tree[0][0].text, None
        else:
            return None, None
    finally:
        page.close()
