# Copyright D J Moore 2007

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


import re
import Cookie
from MoinMoin.user import User

def moinoodle(request, **kw):
    """ authenticate via the Moodle session cookie """
    user_obj   = kw.get('user_obj')
    cookiename = "MoodleSession"

    #log = file("/tmp/moinoodle.out", "w")
    log = None
    if log: log.write("moinoodle authentication\n")
    try:
        cookie = Cookie.SimpleCookie(request.saved_cookie)
    except Cookie.CookieError:
        cookie = None

    if not cookie or not cookie.has_key(cookiename):
        # no cookie, no login
        return user_obj, True

    if log: log.write("got %s cookie\n" % cookiename)
    sessId = cookie[cookiename].value
    sessPath = request.cfg.moodle_session_dir + "/sess_" + sessId
    sessIn = file(sessPath)

    if not sessIn:
        # no session, no login
        return user_obj, True
    if log: log.write("got %s session\n" % sessPath)

    data = sessIn.read()
    #pre-Moodle 1.8 used: match = re.search(r'"loggedin";b:1;', data)
    match = re.search(r'"currentlogin"', data)
    if not match:
        if log: log.write("not logged in!\n")
        return user_obj, True
    if log: log.write("got loggedin flag\n")

    match = re.search(r'"username";s:\d+:"([^"]*)"', data)
    if not match:
        return None, True
    username = match.group(1)
    if log: log.write("username=%s\n" % username)

    match = re.search(r'"firstname";s:\d+:"([^"]*)"', data)
    fullname = ""
    if match:
        fullname = match.group(1)
        match = re.search(r'"lastname";s:\d+:"([^"]*)"', data)
        if match:
            fullname += " " + match.group(1)

    email = ""
    match = re.search(r'"email";s:\d+:"([^"]+@[^"]+)"', data)
    if match:
        email = match.group(1)

    tz = ""
    match = re.search(r'"timezone";s:\d+:"([^"]*)"', data)
    if match:
        tz = match.group(1)
    if log: log.write("fullname=%s email=%s tz=%s\n" % (fullname, email, tz))

    user = User(request, auth_username=username)

    if fullname:
        user.aliasname = fullname
    if email:
        user.email = email
    if tz and tz != "99":
        user.tz_offset = int(float(tz) * 3600)

    user.create_or_update(True)

    if user.valid:
        if log: log.write("Logged in OK!\n")
        return user, False
    else:
        if log: log.write("user not valid?!\n")
        return user_obj, True



