# -*- 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 urlparse
from netaddr import IPNetwork, IPAddress

from MoinMoin.auth import BaseAuth
from MoinMoin.Page import Page
from MoinMoin import user
from anonymous_user import AnonymousAuth

class IpRange(AnonymousAuth):
    name = 'IpRange'

    def __init__(self, auth_username="Connexion", local_nets=[], actions=[], actions_msg={}):
        AnonymousAuth.__init__(self, auth_username=auth_username)
        self.local_nets = local_nets;
        self.actions = actions
        self.actions_msg=actions_msg

    def can_view(self, request):
        try:
            for net in self.local_nets:
                if IPAddress(request.remote_addr) in IPNetwork(net):
                    return True
        except:
            pass
        return False

    def request(self, request, user_obj, **kw):
        user_obj, cont = AnonymousAuth.request(self, request, user_obj, **kw)
        if  not user_obj or not user_obj.valid:
            # Are we trying to do a protected action (eg newaccount)
            action = request.args.get("action", "")
            if action in self.actions:
                if action in self.actions_msg.keys():
                    request.theme.add_msg(self.actions_msg[action])
                p = urlparse.urlparse(request.url)
                url = urlparse.urlunparse(('https', p.netloc, p.path, "", "", ""))
                request.http_redirect(url)

        return user_obj, True


