from mod_python import apache
from mod_python import util
import os

def authenhandler(req, **kwargs):
    """
    Authentication handler that checks if user is logged in
    """

    # mod_python fakes the environ, and thus doesn't process SetEnv.  This fixes
    # that so that the following import works
    os.environ.update(req.subprocess_env)
    
    # check for PythonOptions
    _str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes')
    
    options = req.get_options()
    settings_module = options.get('DJANGO_SETTINGS_MODULE', None)
    if settings_module:
        os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
        
    from django import db
    from django.conf import settings
    from django.core.handlers.modpython import ModPythonRequest
    from django.contrib.auth.middleware import LazyUser
    from django.contrib.sessions.middleware import SessionWrapper
    
    db.reset_queries()

    request = ModPythonRequest(req)
    
    # set session to request    
    request.session = SessionWrapper(request.COOKIES.get(settings.SESSION_COOKIE_NAME, None))
    
    # set user to request
    request.__class__.user = LazyUser()
    
    require_login_path = getattr(settings, 'REQUIRE_LOGIN_PATH', '/accounts/login/')
    
    try:
        if request.path != require_login_path and request.user.is_anonymous():
            util.redirect(req, str('%s?next=%s' % (require_login_path, request.path)))
        else:
            req.user = str(request.user)
            return apache.OK
    except:
        return apache.HTTP_UNAUTHORIZED
    finally:
        db.connection.close()
