from django.parts.auth import anonymoususers
from django.models.auth import users, User
import md5
import datetime

try: 
    from django.conf.settings import \
            REALM_DOMAINS, EMAIL_DEFAULT_TO_REALM, \
            DEFAULT_DOMAIN, PASSWORD_SENTINEL
except ImportError: 
    # These settings adjust the behaviour of the httpdauth.HttpAuth middleware. 
    #
    # To prevent email addresses from being determined, set: 
    #
    # REALM_DOMAINS = {}
    # EMAIL_DEFAULT_TO_REALM = False
    # DEFAULT_DOMAIN = None
    #
    # Otherwise, set: 
    #
    # REALM_DOMAINS maps Kerberos realms to email address domains. 
    REALM_DOMAINS = {} 

    # If the realm lookup fails but EMAIL_DEFAULT_TO_REALM is true, a lowercase 
    # version of the realm will be used as the email address domain. 
    EMAIL_DEFAULT_TO_REALM = False

    # Finally: if EMAIL_DEFAULT_TO_REALM isn't appropriate but there's a single 
    # domain where all the other addresses go, set DEFAULT_DOMAIN. Otherwise, 
    # set it to None. 
    DEFAULT_DOMAIN = None

    # This sentinel is used instead of an MD5 hash in the password field of 
    # the created user record. 
    PASSWORD_SENTINEL = 'XXno_passwordXX' 

class HttpAuth:
    """
    Grabs what the webserver thinks is the logged on user id, 
    and use that instead, creating the record if it doesn't exist in the table.

    There are currently three problems with this at the moment.
     * It doesn't update the last-login 
     * It doesn't update the session cookie 
     * It has no idea what the email address is
    """
    def process_request(self, request):
        "gets REMOTE_USER and sets the userid based on that"
        if request.user.is_anonymous(): 
            remote_user = request.META.get('REMOTE_USER')
            if remote_user is not None: 
                email = email_domain = None
                try: 
                    username, realm = remote_user.split('@')
                    email_domain = REALM_DOMAINS.get(realm.upper())
                    if email_domain is None and EMAIL_DEFAULT_TO_REALM: 
                        email_domain = realm.lower()
                except ValueError: 
                    username = remote_user
                email_domain = email_domain or DEFAULT_DOMAIN
                try:
                    user = users.get_object(username__exact=username)
                except (users.UserDoesNotExist):
                    now = datetime.datetime.now()
                    if email_domain is not None: 
                        email = '%s@%s' % (username, email_domain)
                    user = User(None, username,'','', email, 
                            PASSWORD_SENTINEL, False, True, 
                            False, now, now)
                    user.save()
                request.user= user
        return None

