#-*- encoding: utf-8 -*-

# IMAP auth for MoinMoin, by Cléber Zavadniak
# Based on DummyAuth, by RadomirDopieralski
# (http://moinmo.in/AuthMarket?action=AttachFile&do=view&target=DummyAuth.py)
# (http://moinmo.in/RadomirDopieralski)
#
# Usage: add these lines to your wikiconfig.py:
#
#   from IMAPAuth import IMAPAuth
#   auth = [IMAPAuth(u'stmp.yourserver.com')] 

import imaplib

from MoinMoin import user
from MoinMoin.auth import BaseAuth, CancelLogin, ContinueLogin

class IMAPAuth(BaseAuth):
    """Authenticate users if they authenticate at some IMAP server."""

    name = 'imap'
    logout_possible = True
    login_inputs = ['username', 'password']

    def __init__(self, host, port = 143):
        self.host = host
        self.port = port

    def login_plain (self, imap, user, password, authuser = None):
        def plain_callback (response):
            if authuser is None:
                return "%s\x00%s\x00%s" % ( user , user , password )
            else:
                return "%s\x00%s\x00%s" % ( user , authuser , password )
        
        try:
            return imap.authenticate ('PLAIN', plain_callback)
        except imap.error as e:
            print 'imap error:', e
            return False


    def authenticate (self, request, username, password):

        imap = imaplib.IMAP4(self.host, self.port)
        #print
        #print 'imap capabilities:', imap.capabilities
        resposta = self.login_plain(imap, username, password)

        if resposta and resposta[0] == 'OK' and 'Logged in' in resposta[1]:

            # Cuts off the @server part of the e-mail address:
            clear_username = username.split('@')[0]

            u = user.User(request, auth_username=clear_username, auth_method=self.name, auth_attribs=('username', 'password',))
            u.name = clear_username
            u.remember_me = 0 # 0 enforces cookie_lifetime config param

            u.create_or_update(True)

            return u

        else:
            return False # Invalid credentials!

    def login(self, request, user_obj, **kw):

        _ = request.getText

        username = kw.get('username')
        password = kw.get('password')

        if user_obj:
            pass # Do we have anything to do in this case?
        else:
            u = self.authenticate(request, username, password)
            if u == False:
                return CancelLogin(_("Invalid username or password."))
            else:
                return ContinueLogin(u)

        return ContinueLogin(user_obj)

    def logout(self, request, user_obj, **kw):
        # Faz nada.
        user_obj.valid = False
        return user_obj, False

