# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.conf import settings
from django.utils.translation import ugettext_lazy as _

from django_cas.views import _service_url, _redirect_url, _login_url
import django_cas.middleware
from django.contrib import messages

__all__ = ['login']

def login(request, next_page=None, required=False):
    """Forwards to CAS login URL or verifies CAS ticket"""

    if not next_page:
        next_page = _redirect_url(request)
    if request.user.is_authenticated():
        message = _(u"Vous êtes connecté en tant que %s.") % request.user.username
        messages.success(request, message)
        return HttpResponseRedirect(next_page)
    ticket = request.GET.get('ticket')
    service = _service_url(request, next_page)
    if ticket:
        from django.contrib import auth
        user = auth.authenticate(ticket=ticket, service=service)
        if user is not None:
            auth.login(request, user)
            name = user.first_name or user.username
            message = _(u"Connexion réussie. Bienvenue, %s.") % name
            messages.success(request, message)
            return HttpResponseRedirect(next_page)
        elif settings.CAS_RETRY_LOGIN or required:
            return HttpResponseRedirect(_login_url(service))
        else:
            error = _(u"<h1>Interdit</h1><p>Connexion échouée.</p>")
            return HttpResponseForbidden(error)
    else:
        return HttpResponseRedirect(_login_url(service))

django_cas.middleware.cas_login = login
