from urllib import urlencode
from urlparse import urlparse, urlunparse, parse_qsl

from django.contrib.auth import authenticate, login

from ldt.security import set_current_user

from django.conf import settings

class CASAuthenticationMiddleware(object):
    '''
        Middleware class for authenticating a user through a CAS Server via the CAS Proxy protocol.
        The request must have a "cas_ticket" argument that contains the CAS Proxy ticket to be validated.
        
        Requires django-cas-ng authentication backend.
    '''
    def process_request(self, request):
        ticket = request.GET.get(settings.CAS_URLPARAMETER_NAME)
        if ticket is not None:
            parsed_url = urlparse(request.build_absolute_uri())
            # editing ticket parameter out of the request
            new_query_params = urlencode([param for param in parse_qsl(parsed_url.query) if str(param[0]) != settings.CAS_URLPARAMETER_NAME])
            
            service = urlunparse((
                parsed_url.scheme,
                parsed_url.netloc,
                parsed_url.path,
                parsed_url.params,
                new_query_params,
                parsed_url.fragment
            ))
            
            user = authenticate(ticket=ticket, service=service, request=request)
            if user is None:
                return False
            request.user = user
            login(request, user)
            set_current_user(user)