# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - CAS authentication

    Jasig CAS (see http://www.jasig.org/cas) authentication module.

    @copyright: 2012 MoinMoin:RichardLiao
    @license: GNU GPL, see COPYING for details.
"""

import sys
import os
import time, re
import urlparse
import urllib, urllib2

from MoinMoin import log
logging = log.getLogger(__name__)

from MoinMoin.auth import BaseAuth
from MoinMoin import user, wikiutil
from MoinMoin.Page import Page

from werkzeug import get_host

class AnonymousAuth(BaseAuth):
    name = 'AnonymousAuth'
    login_inputs = []
    logout_possible = False

    def __init__(self, auth_username="Connexion"):
        BaseAuth.__init__(self)
        self.auth_username = auth_username

    def can_view(self, request):
        raise NotImplementedError

    def request(self, request, user_obj, **kw):
        action = request.args.get("action", "")
        # Si l'utilisateur est en train de se connecter
        # On droppe la pseudo connexion anonyme, si elle
        # existe bien.
        if action == 'login':
            if user_obj:
                user_obj.valid = False
            return user_obj, True

        # authenticated user
        if user_obj and user_obj.valid and user_obj.auth_method != self.name and user_obj.name != self.auth_username:
            return user_obj, True

        p = urlparse.urlparse(request.url)
        # Prevent preference edition and quicklink when anonymous
        if action == "userprefs" or action == "quicklink":
	    url = urlparse.urlunparse(('https', p.netloc, p.path, "", "", ""))
            request.http_redirect(url)


        # anonymous
        if self.can_view(request):
            if user_obj and user_obj.valid:
                return user_obj, True
            sys.stderr.write("Authentification anonyme dans %s\n" % self.name)
            u = user.User(request, auth_username=self.auth_username, auth_method=self.name)
            u.auth_username=self.auth_username
            u.name=self.auth_username
            u.valid = True
            u.auth_method = self.name
            u.name = self.auth_username
        elif user_obj and user_obj.valid:
            u=user_obj
            u.valid = False
        else:
            u = user_obj


        # If reach anonymous user personnal page, redirect to referer with action=login
        if p.path == "/%s" % self.auth_username and action != "login":
            referer_p = urlparse.urlparse(request.http_referer)
            if get_host(request.environ) == referer_p.netloc:
                referer_url = urlparse.urlunparse(('https', p.netloc, referer_p.path, "", "", ""))
                request.http_redirect(referer_url + "?action=login")
            else:
                request.http_redirect("https://"+ p.netloc + "/?action=login")

        return u, True

