from django.parts.auth import anonymoususers
from django.models.auth import users, User
import md5
import datetime

DEFAULT_DOMAIN = 'example.com' # added to user ID to create email address
PASSWORD_SENTINEL = 'XXno_passwordXX' # indicates no real password

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: 
                try: 
                    username, realm = remote_user.split('@')
                except ValueError: 
                    username = remote_user
                try:
                    user = users.get_object(username__exact=username)
                except (users.UserDoesNotExist):
                    now = datetime.datetime.now()
                    email = '%s@%s' % (username, DEFAULT_DOMAIN)
                    user = User(None, username,'','', email, 
                            PASSWORD_SENTINEL, False, True, 
                            False, now, now)
                    user.save()
                request.user= user
        return None

