Commits

Valentin Golev  committed daaea77

A lot of tests OK! User can be created, changed

  • Participants
  • Parent commits b243a8d

Comments (0)

Files changed (38)

+[    {        "pk": "1",         "model": "auth.user",         "fields": {            "username": "testclient",             "first_name": "Test",             "last_name": "Client",             "is_active": true,             "is_superuser": false,             "is_staff": false,             "last_login": "2006-12-17 07:03:31",             "groups": [],             "user_permissions": [],             "password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",             "email": "testclient@example.com",             "date_joined": "2006-12-17 07:03:31"        }    },    {        "pk": "2",         "model": "auth.user",         "fields": {            "username": "inactive",             "first_name": "Inactive",             "last_name": "User",             "is_active": false,             "is_superuser": false,             "is_staff": false,             "last_login": "2006-12-17 07:03:31",             "groups": [],             "user_permissions": [],             "password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",             "email": "testclient@example.com",             "date_joined": "2006-12-17 07:03:31"        }    },    {        "pk": "3",         "model": "auth.user",         "fields": {            "username": "staff",             "first_name": "Staff",             "last_name": "Member",             "is_active": true,             "is_superuser": false,             "is_staff": true,             "last_login": "2006-12-17 07:03:31",             "groups": [],             "user_permissions": [],             "password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",             "email": "staffmember@example.com",             "date_joined": "2006-12-17 07:03:31"        }    }]

File mon_django/auth/__init__.py

+import datetime
+from warnings import warn
+from django.core.exceptions import ImproperlyConfigured
+from django.utils.importlib import import_module
+
 SESSION_KEY = '_auth_user_id'
 BACKEND_SESSION_KEY = '_auth_user_backend'
+REDIRECT_FIELD_NAME = 'next'
+
+def load_backend(path):
+    i = path.rfind('.')
+    module, attr = path[:i], path[i+1:]
+    try:
+        mod = import_module(module)
+    except ImportError, e:
+        raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (module, e))
+    except ValueError, e:
+        raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?')
+    try:
+        cls = getattr(mod, attr)
+    except AttributeError:
+        raise ImproperlyConfigured('Module "%s" does not define a "%s" authentication backend' % (module, attr))
+    try:
+        getattr(cls, 'supports_object_permissions')
+    except AttributeError:
+        warn("Authentication backends without a `supports_object_permissions` attribute are deprecated. Please define it in %s." % cls,
+             PendingDeprecationWarning)
+        cls.supports_object_permissions = False
+    try:
+        getattr(cls, 'supports_anonymous_user')
+    except AttributeError:
+        warn("Authentication backends without a `supports_anonymous_user` attribute are deprecated. Please define it in %s." % cls,
+             PendingDeprecationWarning)
+        cls.supports_anonymous_user = False
+    return cls()
+
+def get_backends():
+    from django.conf import settings
+    backends = []
+    for backend_path in settings.AUTHENTICATION_BACKENDS:
+        backends.append(load_backend(backend_path))
+    return backends
 
 def get_user(request):
     from mon_django.auth.models import AnonymousUser
     except KeyError:
         user = AnonymousUser()
     return user
+
+def authenticate(**credentials):
+    """
+    If the given credentials are valid, return a User object.
+    """
+    for backend in get_backends():
+        try:
+            user = backend.authenticate(**credentials)
+        except TypeError:
+            # This backend doesn't accept these credentials as arguments. Try the next one.
+            continue
+        if user is None:
+            continue
+        # Annotate the user object with the path of the backend.
+        user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
+        return user
+
+def login(request, user):
+    """
+    Persist a user id and a backend in the request. This way a user doesn't
+    have to reauthenticate on every request.
+    """
+    if user is None:
+        user = request.user
+    # TODO: It would be nice to support different login methods, like signed cookies.
+    user.last_login = datetime.datetime.now()
+    user.save()
+
+    if SESSION_KEY in request.session:
+        if request.session[SESSION_KEY] != user.id:
+            # To avoid reusing another user's session, create a new, empty
+            # session if the existing session corresponds to a different
+            # authenticated user.
+            request.session.flush()
+    else:
+        request.session.cycle_key()
+    request.session[SESSION_KEY] = user.id
+    request.session[BACKEND_SESSION_KEY] = user.backend
+    if hasattr(request, 'user'):
+        request.user = user

File mon_django/auth/backends.py

+from mon_django.auth.models import User
+
+class RemoteUserBackend(object):
+    pass
+
+class ModelBackend(object):
+    def authenticate(self, username=None, password=None):
+        try:
+            user = User.objects.get(username=username)
+            if user.check_password(password):
+                return user
+        except User.DoesNotExist:
+            return None
+
+    def get_user(self, user_id):
+        try:
+            return User.objects.get(pk=user_id)
+        except User.DoesNotExist:
+            return None

File mon_django/auth/context_processors.py

+from django.core.context_processors import PermWrapper
+from django.utils.functional import lazy, memoize, SimpleLazyObject
+
+def auth(request):
+    """
+    Returns context variables required by apps that use Django's authentication
+    system.
+
+    If there is no 'user' attribute in the request, uses AnonymousUser (from
+    django.contrib.auth).
+    """
+    # If we access request.user, request.session is accessed, which results in
+    # 'Vary: Cookie' being sent in every request that uses this context
+    # processor, which can easily be every request on a site if
+    # TEMPLATE_CONTEXT_PROCESSORS has this context processor added.  This kills
+    # the ability to cache.  So, we carefully ensure these attributes are lazy.
+    # We don't use django.utils.functional.lazy() for User, because that
+    # requires knowing the class of the object we want to proxy, which could
+    # break with custom auth backends.  LazyObject is a less complete but more
+    # flexible solution that is a good enough wrapper for 'User'.
+    def get_user():
+        if hasattr(request, 'user'):
+            return request.user
+        else:
+            from django.contrib.auth.models import AnonymousUser
+            return AnonymousUser()
+
+    return {
+        'user': SimpleLazyObject(get_user),
+#        'messages': messages.get_messages(request),
+        'perms':  lazy(lambda: PermWrapper(get_user()), PermWrapper)(),
+    }

File mon_django/auth/decorators.py

+def login_required(function):
+    return function

File mon_django/auth/forms.py

+from mon_django.auth.models import User
+from mon_django.auth import authenticate
+from mon_django.auth.tokens import default_token_generator
+from django.contrib.sites.models import Site
+from django.template import Context, loader
+from django import forms
+from django.utils.translation import ugettext_lazy as _
+from django.utils.http import int_to_base36
+
+class UserCreationForm(forms.Form):
+    """
+    A form that creates a user, with no privileges, from the given username and password.
+    """
+    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
+        help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
+        error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
+    password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
+    password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,
+        help_text = _("Enter the same password as above, for verification."))
+
+    class Meta:
+        model = User
+        fields = ("username",)
+
+    def clean_username(self):
+        username = self.cleaned_data["username"]
+        try:
+            User.objects.get(username=username)
+        except User.DoesNotExist:
+            return username
+        raise forms.ValidationError(_("A user with that username already exists."))
+
+    def clean_password2(self):
+        password1 = self.cleaned_data.get("password1", "")
+        password2 = self.cleaned_data["password2"]
+        if password1 != password2:
+            raise forms.ValidationError(_("The two password fields didn't match."))
+        return password2
+
+    def save(self, commit=True):
+        user = super(UserCreationForm, self).save(commit=False)
+        user.set_password(self.cleaned_data["password1"])
+        if commit:
+            user.save()
+        return user
+
+class UserChangeForm(forms.Form):
+    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
+        help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
+        error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
+
+    class Meta:
+        model = User
+
+class AuthenticationForm(forms.Form):
+    """
+    Base class for authenticating users. Extend this to get a form that accepts
+    username/password logins.
+    """
+    username = forms.CharField(label=_("Username"), max_length=30)
+    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
+
+    def __init__(self, request=None, *args, **kwargs):
+        """
+        If request is passed in, the form will validate that cookies are
+        enabled. Note that the request (a HttpRequest object) must have set a
+        cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
+        running this validation.
+        """
+        self.request = request
+        self.user_cache = None
+        super(AuthenticationForm, self).__init__(*args, **kwargs)
+
+    def clean(self):
+        username = self.cleaned_data.get('username')
+        password = self.cleaned_data.get('password')
+
+        if username and password:
+            self.user_cache = authenticate(username=username, password=password)
+            if self.user_cache is None:
+                raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
+            elif not self.user_cache.is_active:
+                raise forms.ValidationError(_("This account is inactive."))
+
+        # TODO: determine whether this should move to its own method.
+        if self.request:
+            if not self.request.session.test_cookie_worked():
+                raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
+
+        return self.cleaned_data
+
+    def get_user_id(self):
+        if self.user_cache:
+            return self.user_cache.id
+        return None
+
+    def get_user(self):
+        return self.user_cache
+
+class PasswordResetForm(forms.Form):
+    email = forms.EmailField(label=_("E-mail"), max_length=75)
+
+    def clean_email(self):
+        """
+        Validates that a user exists with the given e-mail address.
+        """
+        email = self.cleaned_data["email"]
+        self.users_cache = User.objects.filter(email__iexact=email)
+        if len(self.users_cache) == 0:
+            raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
+        return email
+
+    def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
+             use_https=False, token_generator=default_token_generator):
+        """
+        Generates a one-use only link for resetting password and sends to the user
+        """
+        from django.core.mail import send_mail
+        for user in self.users_cache:
+            if not domain_override:
+                current_site = Site.objects.get_current()
+                site_name = current_site.name
+                domain = current_site.domain
+            else:
+                site_name = domain = domain_override
+            t = loader.get_template(email_template_name)
+            c = {
+                'email': user.email,
+                'domain': domain,
+                'site_name': site_name,
+                'uid': int_to_base36(user.id),
+                'user': user,
+                'token': token_generator.make_token(user),
+                'protocol': use_https and 'https' or 'http',
+            }
+            send_mail(_("Password reset on %s") % site_name,
+                t.render(Context(c)), None, [user.email])
+
+class SetPasswordForm(forms.Form):
+    """
+    A form that lets a user change set his/her password without
+    entering the old password
+    """
+    new_password1 = forms.CharField(label=_("New password"), widget=forms.PasswordInput)
+    new_password2 = forms.CharField(label=_("New password confirmation"), widget=forms.PasswordInput)
+
+    def __init__(self, user, *args, **kwargs):
+        self.user = user
+        super(SetPasswordForm, self).__init__(*args, **kwargs)
+
+    def clean_new_password2(self):
+        password1 = self.cleaned_data.get('new_password1')
+        password2 = self.cleaned_data.get('new_password2')
+        if password1 and password2:
+            if password1 != password2:
+                raise forms.ValidationError(_("The two password fields didn't match."))
+        return password2
+
+    def save(self, commit=True):
+        self.user.set_password(self.cleaned_data['new_password1'])
+        if commit:
+            self.user.save()
+        return self.user
+
+class PasswordChangeForm(SetPasswordForm):
+    """
+    A form that lets a user change his/her password by entering
+    their old password.
+    """
+    old_password = forms.CharField(label=_("Old password"), widget=forms.PasswordInput)
+
+    def clean_old_password(self):
+        """
+        Validates that the old_password field is correct.
+        """
+        old_password = self.cleaned_data["old_password"]
+        if not self.user.check_password(old_password):
+            raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
+        return old_password
+PasswordChangeForm.base_fields.keyOrder = ['old_password', 'new_password1', 'new_password2']
+
+class AdminPasswordChangeForm(forms.Form):
+    """
+    A form used to change the password of a user in the admin interface.
+    """
+    password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
+    password2 = forms.CharField(label=_("Password (again)"), widget=forms.PasswordInput)
+
+    def __init__(self, user, *args, **kwargs):
+        self.user = user
+        super(AdminPasswordChangeForm, self).__init__(*args, **kwargs)
+
+    def clean_password2(self):
+        password1 = self.cleaned_data.get('password1')
+        password2 = self.cleaned_data.get('password2')
+        if password1 and password2:
+            if password1 != password2:
+                raise forms.ValidationError(_("The two password fields didn't match."))
+        return password2
+
+    def save(self, commit=True):
+        """
+        Saves the new password.
+        """
+        self.user.set_password(self.cleaned_data["password1"])
+        if commit:
+            self.user.save()
+        return self.user
+

File mon_django/auth/models.py

-from django.contrib.auth.models import AnonymousUser
+import datetime
+
+from django.utils.encoding import smart_str
+from django.utils.hashcompat import md5_constructor, sha_constructor
+
+from django.core import exceptions
+
+from mon_django.core import get_db
+
+UNUSABLE_PASSWORD = '!' # This will never be a valid hash
+
+def get_hexdigest(algorithm, salt, raw_password):
+    """
+    Returns a string of the hexdigest of the given plaintext password and salt
+    using the given algorithm ('md5', 'sha1' or 'crypt').
+    """
+    raw_password, salt = smart_str(raw_password), smart_str(salt)
+    if algorithm == 'crypt':
+        try:
+            import crypt
+        except ImportError:
+            raise ValueError('"crypt" password algorithm not supported in this environment')
+        return crypt.crypt(raw_password, salt)
+
+    if algorithm == 'md5':
+        return md5_constructor(salt + raw_password).hexdigest()
+    elif algorithm == 'sha1':
+        return sha_constructor(salt + raw_password).hexdigest()
+    raise ValueError("Got unknown password algorithm type in password.")
+
+
+class UserManager(object):
+    def __init__(self, model=None):
+        if model:
+            self.model = model
+
+    def create_user(self, username, email, password=None):
+        """
+        Creates and saves a User with the given username, e-mail and password.
+        """
+
+        now = datetime.datetime.now()
+        
+        # Normalize the address by lowercasing the domain part of the email
+        # address.
+        try:
+            email_name, domain_part = email.strip().split('@', 1)
+        except ValueError:
+            pass
+        else:
+            email = '@'.join([email_name, domain_part.lower()])
+
+        user = self.model(username=username, email=email, is_staff=False,
+                         is_active=True, is_superuser=False, last_login=now,
+                         date_joined=now)
+
+        if password:
+            user.set_password(password)
+        else:
+            user.set_unusable_password()
+        user.save()
+        return user 
+
+    def get_collection(self):
+        collection = get_db()['mon_django__auth__users']
+        collection.ensure_index('username', unique=True)
+        return collection
+
+    def get(self, **kwargs):
+        query = {}
+
+        for p in kwargs.iterkeys():
+            if p == 'pk' or p == 'id':
+                query['_id'] = kwargs[p]
+            elif p in self.model.valid_params:
+                query[p] = kwargs[p]
+            else:
+                raise TypeError("'%s' is an invalid keyword argument for this function" % p) 
+
+        result = self.get_collection().find(query)
+        num = result.count()
+        if num == 1:
+            results = result[0]
+            return User(**result[0])
+        
+        if not num:
+            raise self.model.DoesNotExist("User matching query does not exist.") 
+
+        raise self.model.MultipleObjectsReturned("get() returned more than one User -- it returned %s! Lookup parameters were %s"
+                % (num, kwargs))
+
+class User(object):
+    objects = UserManager()
+
+    valid_params = ('username', 'first_name', 'last_name', 'email', 'password',
+                    'is_staff', 'is_active', 'is_superuser', 'last_login',
+                    'date_joined', 'groups', 'user_permissions', '_id')
+
+    valid_attrs = ('_params', 'backend')
+
+    DoesNotExist = exceptions.ObjectDoesNotExist
+    MultipleObjectsReturned = exceptions.MultipleObjectsReturned
+
+    def __init__(self, **kwargs):
+        self._params = {}
+        for p in kwargs.iterkeys():
+            if p in self.valid_params:
+                self._params[p] = kwargs[p]
+            else:
+                raise TypeError("'%s' is an invalid keyword argument for this function" % p) 
+
+    def __getattr__(self, name):
+        if name == 'id' or name == 'pk':
+            name = '_id'
+        if name in self.valid_attrs:
+            return object.__getattr__(self, name)
+        if not name in self.valid_params:
+            raise AttributeError("'User' object has no attribute '%s'" % name)
+        try:
+            return self._params[name]
+        except KeyError:
+            return '' # TODO: Create defaults.
+        
+    def __setattr__(self, name, value):
+        if name == 'id' or name == 'pk':
+            name = '_id'
+        if name in self.valid_attrs:
+            object.__setattr__(self, name, value)
+            return
+        if not name in self.valid_params:
+            raise AttributeError("'User' object has no attribute '%s'" % name)
+        self._params[name] = value
+
+    def set_password(self, raw_password):
+        import random
+        algo = 'sha1'
+        salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
+        hsh = get_hexdigest(algo, salt, raw_password)
+        self.password = '%s$%s$%s' % (algo, salt, hsh)
+
+    def save(self):
+        self.objects.get_collection().save(self._params)
+
+    def check_password(self, raw_password):
+        """
+        Returns a boolean of whether the raw_password was correct. Handles
+        encryption formats behind the scenes.
+        """
+        # Backwards-compatibility check. Older passwords won't include the
+        # algorithm or salt.
+        if '$' not in self.password:
+            is_correct = (self.password == get_hexdigest('md5', '', raw_password))
+            if is_correct:
+                # Convert the password to the new, more secure format.
+                self.set_password(raw_password)
+                self.save()
+            return is_correct
+        return check_password(raw_password, self.password)
+
+
+UserManager.model = User
+
+def check_password(raw_password, enc_password):
+    """
+    Returns a boolean of whether the raw_password was correct. Handles
+    encryption formats behind the scenes.
+    """
+    algo, salt, hsh = enc_password.split('$')
+    return hsh == get_hexdigest(algo, salt, raw_password)
+
+class Group(object):
+    pass
+
+class Permission(object):
+    pass
+
+class SiteProfileNotAvailable(Exception):
+    pass
+
+class EmptyManager(UserManager):
+    def get_query_set(self):
+        return self.get_empty_query_set()
+
+class AnonymousUser(object):
+    id = None
+    username = ''
+    is_staff = False
+    is_active = False
+    is_superuser = False
+    _groups = EmptyManager()
+    _user_permissions = EmptyManager()
+
+    def __init__(self):
+        pass
+
+    def __unicode__(self):
+        return 'AnonymousUser'
+
+    def __str__(self):
+        return unicode(self).encode('utf-8')
+
+    def __eq__(self, other):
+        return isinstance(other, self.__class__)
+
+    def __ne__(self, other):
+        return not self.__eq__(other)
+
+    def __hash__(self):
+        return 1 # instances always return the same hash value
+
+    def save(self):
+        raise NotImplementedError
+
+    def delete(self):
+        raise NotImplementedError
+
+    def set_password(self, raw_password):
+        raise NotImplementedError
+
+    def check_password(self, raw_password):
+        raise NotImplementedError
+
+    def _get_groups(self):
+        return self._groups
+    groups = property(_get_groups)
+
+    def _get_user_permissions(self):
+        return self._user_permissions
+    user_permissions = property(_get_user_permissions)
+
+    def get_group_permissions(self, obj=None):
+        return set()
+
+    def get_all_permissions(self, obj=None):
+        return _user_get_all_permissions(self, obj=obj)
+
+    def has_perm(self, perm, obj=None):
+        return _user_has_perm(self, perm, obj=obj)
+
+    def has_perms(self, perm_list, obj=None):
+        for perm in perm_list:
+            if not self.has_perm(perm, obj):
+                return False
+        return True
+
+    def has_module_perms(self, module):
+        return _user_has_module_perms(self, module)
+
+    def get_and_delete_messages(self):
+        return []
+
+    def is_anonymous(self):
+        return True
+
+    def is_authenticated(self):
+        return False

File mon_django/auth/mongo_fixtures/authtestdata.json

+[
+    {
+        "pk": "1", 
+        "model": "auth.user", 
+        "fields": {
+            "username": "testclient", 
+            "first_name": "Test", 
+            "last_name": "Client", 
+            "is_active": true, 
+            "is_superuser": false, 
+            "is_staff": false, 
+            "last_login": "2006-12-17 07:03:31", 
+            "groups": [], 
+            "user_permissions": [], 
+            "password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161", 
+            "email": "testclient@example.com", 
+            "date_joined": "2006-12-17 07:03:31"
+        }
+    },
+    {
+        "pk": "2", 
+        "model": "auth.user", 
+        "fields": {
+            "username": "inactive", 
+            "first_name": "Inactive", 
+            "last_name": "User", 
+            "is_active": false, 
+            "is_superuser": false, 
+            "is_staff": false, 
+            "last_login": "2006-12-17 07:03:31", 
+            "groups": [], 
+            "user_permissions": [], 
+            "password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161", 
+            "email": "testclient@example.com", 
+            "date_joined": "2006-12-17 07:03:31"
+        }
+    },
+    {
+        "pk": "3", 
+        "model": "auth.user", 
+        "fields": {
+            "username": "staff", 
+            "first_name": "Staff", 
+            "last_name": "Member", 
+            "is_active": true, 
+            "is_superuser": false, 
+            "is_staff": true, 
+            "last_login": "2006-12-17 07:03:31", 
+            "groups": [], 
+            "user_permissions": [], 
+            "password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161", 
+            "email": "staffmember@example.com", 
+            "date_joined": "2006-12-17 07:03:31"
+        }
+    }
+]

File mon_django/auth/templates/registration/logged_out.html

+{% load i18n %}
+
+<p>{% trans "Thanks for spending some quality time with the Web site today." %}</p>
+
+<p><a href="../">{% trans 'Log in again' %}</a></p>

File mon_django/auth/templates/registration/password_change_done.html

+{% extends "admin/base_site.html" %}
+{% load i18n %}
+<h1>{% trans 'Password change successful' %}</h1>
+
+<p>{% trans 'Your password was changed.' %}</p>

File mon_django/auth/templates/registration/password_change_form.html

+{% load i18n  %}
+
+<form action="" method="post">{% csrf_token %}
+<div>
+{% if form.errors %}
+    <p class="errornote">
+    {% blocktrans count form.errors.items|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}
+    </p>
+{% endif %}
+
+<h1>{% trans 'Password change' %}</h1>
+
+<p>{% trans "Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly." %}</p>
+
+<fieldset class="module aligned wide">
+
+<div class="form-row">
+    {{ form.old_password.errors }}
+    <label for="id_old_password" class="required">{% trans 'Old password' %}:</label>{{ form.old_password }}
+</div>
+
+<div class="form-row">
+    {{ form.new_password1.errors }}
+    <label for="id_new_password1" class="required">{% trans 'New password' %}:</label>{{ form.new_password1 }}
+</div>
+
+<div class="form-row">
+{{ form.new_password2.errors }}
+    <label for="id_new_password2" class="required">{% trans 'Password (again)' %}:</label>{{ form.new_password2 }}
+</div>
+
+</fieldset>
+
+<div class="submit-row">
+    <input type="submit" value="{% trans 'Change my password' %}" class="default" />
+</div>
+
+</div>
+</form>
+

File mon_django/auth/templates/registration/password_reset_complete.html

+{% extends "admin/base_site.html" %}
+{% load i18n %}
+
+{% block breadcrumbs %}<div class="breadcrumbs"><a href="../../">{% trans 'Home' %}</a> &rsaquo; {% trans 'Password reset' %}</div>{% endblock %}
+
+{% block title %}{% trans 'Password reset complete' %}{% endblock %}
+
+{% block content %}
+
+<h1>{% trans 'Password reset complete' %}</h1>
+
+<p>{% trans "Your password has been set.  You may go ahead and log in now." %}</p>
+
+<p><a href="{{ login_url }}">{% trans 'Log in' %}</a></p>
+
+{% endblock %}

File mon_django/auth/templates/registration/password_reset_confirm.html

+{% extends "admin/base_site.html" %}
+{% load i18n %}
+
+{% block breadcrumbs %}<div class="breadcrumbs"><a href="../">{% trans 'Home' %}</a> &rsaquo; {% trans 'Password reset confirmation' %}</div>{% endblock %}
+
+{% block title %}{% trans 'Password reset' %}{% endblock %}
+
+{% block content %}
+
+{% if validlink %}
+
+<h1>{% trans 'Enter new password' %}</h1>
+
+<p>{% trans "Please enter your new password twice so we can verify you typed it in correctly." %}</p>
+
+<form action="" method="post">{% csrf_token %}
+{{ form.new_password1.errors }}
+<p class="aligned wide"><label for="id_new_password1">{% trans 'New password:' %}</label>{{ form.new_password1 }}</p>
+{{ form.new_password2.errors }}
+<p class="aligned wide"><label for="id_new_password2">{% trans 'Confirm password:' %}</label>{{ form.new_password2 }}</p>
+<p><input type="submit" value="{% trans 'Change my password' %}" /></p>
+</form>
+
+{% else %}
+
+<h1>{% trans 'Password reset unsuccessful' %}</h1>
+
+<p>{% trans "The password reset link was invalid, possibly because it has already been used.  Please request a new password reset." %}</p>
+
+{% endif %}
+
+{% endblock %}

File mon_django/auth/templates/registration/password_reset_done.html

+{% extends "admin/base_site.html" %}
+{% load i18n %}
+
+{% block breadcrumbs %}<div class="breadcrumbs"><a href="../">{% trans 'Home' %}</a> &rsaquo; {% trans 'Password reset' %}</div>{% endblock %}
+
+{% block title %}{% trans 'Password reset successful' %}{% endblock %}
+
+{% block content %}
+
+<h1>{% trans 'Password reset successful' %}</h1>
+
+<p>{% trans "We've e-mailed you instructions for setting your password to the e-mail address you submitted. You should be receiving it shortly." %}</p>
+
+{% endblock %}

File mon_django/auth/templates/registration/password_reset_email.html

+{% load i18n %}{% autoescape off %}
+{% trans "You're receiving this e-mail because you requested a password reset" %}
+{% blocktrans %}for your user account at {{ site_name }}{% endblocktrans %}.
+
+{% trans "Please go to the following page and choose a new password:" %}
+{% block reset_link %}
+{{ protocol }}://{{ domain }}{% url django.contrib.auth.views.password_reset_confirm uidb36=uid token=token %}
+{% endblock %}
+{% trans "Your username, in case you've forgotten:" %} {{ user.username }}
+
+{% trans "Thanks for using our site!" %}
+
+{% blocktrans %}The {{ site_name }} team{% endblocktrans %}
+
+{% endautoescape %}

File mon_django/auth/templates/registration/password_reset_form.html

+{% load i18n %}
+
+<h1>{% trans "Password reset" %}</h1>
+
+<p>{% trans "Forgotten your password? Enter your e-mail address below, and we'll e-mail instructions for setting a new one." %}</p>
+
+<form action="" method="post">{% csrf_token %}
+{{ form.email.errors }}
+<p><label for="id_email">{% trans 'E-mail address:' %}</label> {{ form.email }} <input type="submit" value="{% trans 'Reset my password' %}" /></p>
+</form>
+

File mon_django/auth/tests.py

-from django.test import TestCase
-
-
-__test__ = {"doctest": """
->>> from mon_django.auth.models import AnonymousUser
->>> a = AnonymousUser()
->>> a.is_authenticated()
-False
->>> a.is_staff
-False
->>> a.is_active
-False
->>> a.is_superuser
-False
->>> a.groups.all()
-[]
->>> a.user_permissions.all()
-[]
-"""}
-

File mon_django/auth/tests/__init__.py

+#from mon_django.auth.tests.auth_backends import BackendTest, RowlevelBackendTest, AnonymousUserBackendTest, NoAnonymousUserBackendTest
+from mon_django.auth.tests.basic import BASIC_TESTS
+from mon_django.auth.tests.decorators import LoginRequiredTestCase
+from mon_django.auth.tests.forms import FORM_TESTS
+from mon_django.auth.tests.remote_user \
+        import RemoteUserTest, RemoteUserNoCreateTest, RemoteUserCustomTest
+from mon_django.auth.tests.models import ProfileTestCase
+from mon_django.auth.tests.tokens import TOKEN_GENERATOR_TESTS
+from mon_django.auth.tests.views \
+        import PasswordResetTest, ChangePasswordTest, LoginTest, LogoutTest
+
+# The password for the fixture data users is 'password'
+
+__test__ = {
+    'BASIC_TESTS': BASIC_TESTS,
+    'FORM_TESTS': FORM_TESTS,
+    'TOKEN_GENERATOR_TESTS': TOKEN_GENERATOR_TESTS,
+}

File mon_django/auth/tests/auth_backends.py

+from django.conf import settings
+from mon_django.auth.models import User, Group, Permission, AnonymousUser
+from django.contrib.contenttypes.models import ContentType
+from django.test import TestCase
+
+
+class BackendTest(TestCase):
+
+    backend = 'mon_django.auth.backends.ModelBackend'
+
+    def setUp(self):
+        self.curr_auth = settings.AUTHENTICATION_BACKENDS
+        settings.AUTHENTICATION_BACKENDS = (self.backend,)
+        User.objects.create_user('test', 'test@example.com', 'test')
+
+    def tearDown(self):
+        settings.AUTHENTICATION_BACKENDS = self.curr_auth
+
+    def test_has_perm(self):
+        user = User.objects.get(username='test')
+        self.assertEqual(user.has_perm('auth.test'), False)
+        user.is_staff = True
+        user.save()
+        self.assertEqual(user.has_perm('auth.test'), False)
+        user.is_superuser = True
+        user.save()
+        self.assertEqual(user.has_perm('auth.test'), True)
+        user.is_staff = False
+        user.is_superuser = False
+        user.save()
+        self.assertEqual(user.has_perm('auth.test'), False)
+        user.is_staff = True
+        user.is_superuser = True
+        user.is_active = False
+        user.save()
+        self.assertEqual(user.has_perm('auth.test'), False)
+
+    def test_custom_perms(self):
+        user = User.objects.get(username='test')
+        content_type=ContentType.objects.get_for_model(Group)
+        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
+        user.user_permissions.add(perm)
+        user.save()
+
+        # reloading user to purge the _perm_cache
+        user = User.objects.get(username='test')
+        self.assertEqual(user.get_all_permissions() == set([u'auth.test']), True)
+        self.assertEqual(user.get_group_permissions(), set([]))
+        self.assertEqual(user.has_module_perms('Group'), False)
+        self.assertEqual(user.has_module_perms('auth'), True)
+        perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2')
+        user.user_permissions.add(perm)
+        user.save()
+        perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3')
+        user.user_permissions.add(perm)
+        user.save()
+        user = User.objects.get(username='test')
+        self.assertEqual(user.get_all_permissions(), set([u'auth.test2', u'auth.test', u'auth.test3']))
+        self.assertEqual(user.has_perm('test'), False)
+        self.assertEqual(user.has_perm('auth.test'), True)
+        self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True)
+        perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group')
+        group = Group.objects.create(name='test_group')
+        group.permissions.add(perm)
+        group.save()
+        user.groups.add(group)
+        user = User.objects.get(username='test')
+        exp = set([u'auth.test2', u'auth.test', u'auth.test3', u'auth.test_group'])
+        self.assertEqual(user.get_all_permissions(), exp)
+        self.assertEqual(user.get_group_permissions(), set([u'auth.test_group']))
+        self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True)
+
+        user = AnonymousUser()
+        self.assertEqual(user.has_perm('test'), False)
+        self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), False)
+
+    def test_has_no_object_perm(self):
+        """Regressiontest for #12462"""
+        user = User.objects.get(username='test')
+        content_type=ContentType.objects.get_for_model(Group)
+        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
+        user.user_permissions.add(perm)
+        user.save()
+
+        self.assertEqual(user.has_perm('auth.test', 'object'), False)
+        self.assertEqual(user.get_all_permissions('object'), set([]))
+        self.assertEqual(user.has_perm('auth.test'), True)
+        self.assertEqual(user.get_all_permissions(), set(['auth.test']))
+
+
+class TestObj(object):
+    pass
+
+
+class SimpleRowlevelBackend(object):
+    supports_object_permissions = True
+
+    # This class also supports tests for anonymous user permissions,
+    # via subclasses which just set the 'supports_anonymous_user' attribute.
+
+    def has_perm(self, user, perm, obj=None):
+        if not obj:
+            return # We only support row level perms
+
+        if isinstance(obj, TestObj):
+            if user.username == 'test2':
+                return True
+            elif user.is_anonymous() and perm == 'anon':
+                # not reached due to supports_anonymous_user = False
+                return True
+        return False
+
+    def has_module_perms(self, user, app_label):
+        return app_label == "app1"
+
+    def get_all_permissions(self, user, obj=None):
+        if not obj:
+            return [] # We only support row level perms
+
+        if not isinstance(obj, TestObj):
+            return ['none']
+
+        if user.is_anonymous():
+            return ['anon']
+        if user.username == 'test2':
+            return ['simple', 'advanced']
+        else:
+            return ['simple']
+
+    def get_group_permissions(self, user, obj=None):
+        if not obj:
+            return # We only support row level perms
+
+        if not isinstance(obj, TestObj):
+            return ['none']
+
+        if 'test_group' in [group.name for group in user.groups.all()]:
+            return ['group_perm']
+        else:
+            return ['none']
+
+
+class RowlevelBackendTest(TestCase):
+    """
+    Tests for auth backend that supports object level permissions
+    """
+    backend = 'mon_django.auth.tests.auth_backends.SimpleRowlevelBackend'
+
+    def setUp(self):
+        self.curr_auth = settings.AUTHENTICATION_BACKENDS
+        settings.AUTHENTICATION_BACKENDS = self.curr_auth + (self.backend,)
+        self.user1 = User.objects.create_user('test', 'test@example.com', 'test')
+        self.user2 = User.objects.create_user('test2', 'test2@example.com', 'test')
+        self.user3 = User.objects.create_user('test3', 'test3@example.com', 'test')
+
+    def tearDown(self):
+        settings.AUTHENTICATION_BACKENDS = self.curr_auth
+
+    def test_has_perm(self):
+        self.assertEqual(self.user1.has_perm('perm', TestObj()), False)
+        self.assertEqual(self.user2.has_perm('perm', TestObj()), True)
+        self.assertEqual(self.user2.has_perm('perm'), False)
+        self.assertEqual(self.user2.has_perms(['simple', 'advanced'], TestObj()), True)
+        self.assertEqual(self.user3.has_perm('perm', TestObj()), False)
+        self.assertEqual(self.user3.has_perm('anon', TestObj()), False)
+        self.assertEqual(self.user3.has_perms(['simple', 'advanced'], TestObj()), False)
+
+    def test_get_all_permissions(self):
+        self.assertEqual(self.user1.get_all_permissions(TestObj()), set(['simple']))
+        self.assertEqual(self.user2.get_all_permissions(TestObj()), set(['simple', 'advanced']))
+        self.assertEqual(self.user2.get_all_permissions(), set([]))
+
+    def test_get_group_permissions(self):
+        content_type=ContentType.objects.get_for_model(Group)
+        group = Group.objects.create(name='test_group')
+        self.user3.groups.add(group)
+        self.assertEqual(self.user3.get_group_permissions(TestObj()), set(['group_perm']))
+
+
+class AnonymousUserBackend(SimpleRowlevelBackend):
+
+    supports_anonymous_user = True
+
+
+class NoAnonymousUserBackend(SimpleRowlevelBackend):
+
+    supports_anonymous_user = False
+
+
+class AnonymousUserBackendTest(TestCase):
+    """
+    Tests for AnonymousUser delegating to backend if it has 'supports_anonymous_user' = True
+    """
+
+    backend = 'mon_django.auth.tests.auth_backends.AnonymousUserBackend'
+
+    def setUp(self):
+        self.curr_auth = settings.AUTHENTICATION_BACKENDS
+        settings.AUTHENTICATION_BACKENDS = (self.backend,)
+        self.user1 = AnonymousUser()
+
+    def tearDown(self):
+        settings.AUTHENTICATION_BACKENDS = self.curr_auth
+
+    def test_has_perm(self):
+        self.assertEqual(self.user1.has_perm('perm', TestObj()), False)
+        self.assertEqual(self.user1.has_perm('anon', TestObj()), True)
+
+    def test_has_perms(self):
+        self.assertEqual(self.user1.has_perms(['anon'], TestObj()), True)
+        self.assertEqual(self.user1.has_perms(['anon', 'perm'], TestObj()), False)
+
+    def test_has_module_perms(self):
+        self.assertEqual(self.user1.has_module_perms("app1"), True)
+        self.assertEqual(self.user1.has_module_perms("app2"), False)
+
+    def test_get_all_permissions(self):
+        self.assertEqual(self.user1.get_all_permissions(TestObj()), set(['anon']))
+
+
+class NoAnonymousUserBackendTest(TestCase):
+    """
+    Tests that AnonymousUser does not delegate to backend if it has 'supports_anonymous_user' = False
+    """
+    backend = 'mon_django.auth.tests.auth_backends.NoAnonymousUserBackend'
+
+    def setUp(self):
+        self.curr_auth = settings.AUTHENTICATION_BACKENDS
+        settings.AUTHENTICATION_BACKENDS = self.curr_auth + (self.backend,)
+        self.user1 = AnonymousUser()
+
+    def tearDown(self):
+        settings.AUTHENTICATION_BACKENDS = self.curr_auth
+
+    def test_has_perm(self):
+        self.assertEqual(self.user1.has_perm('perm', TestObj()), False)
+        self.assertEqual(self.user1.has_perm('anon', TestObj()), False)
+
+    def test_has_perms(self):
+        self.assertEqual(self.user1.has_perms(['anon'], TestObj()), False)
+
+    def test_has_module_perms(self):
+        self.assertEqual(self.user1.has_module_perms("app1"), False)
+        self.assertEqual(self.user1.has_module_perms("app2"), False)
+
+    def test_get_all_permissions(self):
+        self.assertEqual(self.user1.get_all_permissions(TestObj()), set())

File mon_django/auth/tests/basic.py

+
+BASIC_TESTS = """
+>>> from mon_django.auth.models import User, AnonymousUser
+>>> u = User.objects.create_user('testuser', 'test@example.com', 'testpw')
+>>> u.has_usable_password()
+True
+>>> u.check_password('bad')
+False
+>>> u.check_password('testpw')
+True
+>>> u.set_unusable_password()
+>>> u.save()
+>>> u.check_password('testpw')
+False
+>>> u.has_usable_password()
+False
+>>> u2 = User.objects.create_user('testuser2', 'test2@example.com')
+>>> u2.has_usable_password()
+False
+
+>>> u.is_authenticated()
+True
+>>> u.is_staff
+False
+>>> u.is_active
+True
+>>> u.is_superuser
+False
+
+>>> a = AnonymousUser()
+>>> a.is_authenticated()
+False
+>>> a.is_staff
+False
+>>> a.is_active
+False
+>>> a.is_superuser
+False
+>>> a.groups.all()
+[]
+>>> a.user_permissions.all()
+[]
+
+# superuser tests.
+>>> super = User.objects.create_superuser('super', 'super@example.com', 'super')
+>>> super.is_superuser
+True
+>>> super.is_active
+True
+>>> super.is_staff
+True
+
+#
+# Tests for createsuperuser management command.
+# It's nearly impossible to test the interactive mode -- a command test helper
+# would be needed (and *awesome*) -- so just test the non-interactive mode.
+# This covers most of the important validation, but not all.
+#
+>>> from django.core.management import call_command
+
+>>> call_command("createsuperuser", interactive=False, username="joe", email="joe@somewhere.org")
+Superuser created successfully.
+
+>>> u = User.objects.get(username="joe")
+>>> u.email
+u'joe@somewhere.org'
+>>> u.password
+u'!'
+"""

File mon_django/auth/tests/decorators.py

+from unittest import TestCase
+
+from mon_django.auth.decorators import login_required
+
+
+class LoginRequiredTestCase(TestCase):
+    """
+    Tests the login_required decorators
+    """
+    def testCallable(self):
+        """
+        Check that login_required is assignable to callable objects.
+        """
+        class CallableView(object):
+            def __call__(self, *args, **kwargs):
+                pass
+        login_required(CallableView())
+        
+    def testView(self):
+        """
+        Check that login_required is assignable to normal views.
+        """
+        def normal_view(request):
+            pass
+        login_required(normal_view)

File mon_django/auth/tests/forms.py

+
+FORM_TESTS = """
+>>> from mon_django.auth.models import User
+>>> from mon_django.auth.forms import UserCreationForm, AuthenticationForm
+>>> from mon_django.auth.forms import PasswordChangeForm, SetPasswordForm
+
+# The user already exists.
+
+>>> user = User.objects.create_user("jsmith", "jsmith@example.com", "test123")
+>>> data = {
+...     'username': 'jsmith',
+...     'password1': 'test123',
+...     'password2': 'test123',
+... }
+>>> form = UserCreationForm(data)
+>>> form.is_valid()
+False
+>>> form["username"].errors
+[u'A user with that username already exists.']
+
+# The username contains invalid data.
+
+>>> data = {
+...     'username': 'jsmith!',
+...     'password1': 'test123',
+...     'password2': 'test123',
+... }
+>>> form = UserCreationForm(data)
+>>> form.is_valid()
+False
+>>> form["username"].errors
+[u'This value may contain only letters, numbers and @/./+/-/_ characters.']
+
+# The verification password is incorrect.
+
+>>> data = {
+...     'username': 'jsmith2',
+...     'password1': 'test123',
+...     'password2': 'test',
+... }
+>>> form = UserCreationForm(data)
+>>> form.is_valid()
+False
+>>> form["password2"].errors
+[u"The two password fields didn't match."]
+
+# One (or both) passwords weren't given
+
+>>> data = {'username': 'jsmith2'}
+>>> form = UserCreationForm(data)
+>>> form.is_valid()
+False
+>>> form['password1'].errors
+[u'This field is required.']
+>>> form['password2'].errors
+[u'This field is required.']
+
+>>> data['password2'] = 'test123'
+>>> form = UserCreationForm(data)
+>>> form.is_valid()
+False
+>>> form['password1'].errors
+[u'This field is required.']
+
+# The success case.
+
+>>> data = {
+...     'username': 'jsmith2@example.com',
+...     'password1': 'test123',
+...     'password2': 'test123',
+... }
+>>> form = UserCreationForm(data)
+>>> form.is_valid()
+True
+>>> form.save()
+<User: jsmith2@example.com>
+
+# The user submits an invalid username.
+
+>>> data = {
+...     'username': 'jsmith_does_not_exist',
+...     'password': 'test123',
+... }
+
+>>> form = AuthenticationForm(None, data)
+>>> form.is_valid()
+False
+>>> form.non_field_errors()
+[u'Please enter a correct username and password. Note that both fields are case-sensitive.']
+
+# The user is inactive.
+
+>>> data = {
+...     'username': 'jsmith',
+...     'password': 'test123',
+... }
+>>> user.is_active = False
+>>> user.save()
+>>> form = AuthenticationForm(None, data)
+>>> form.is_valid()
+False
+>>> form.non_field_errors()
+[u'This account is inactive.']
+
+>>> user.is_active = True
+>>> user.save()
+
+# The success case
+
+>>> form = AuthenticationForm(None, data)
+>>> form.is_valid()
+True
+>>> form.non_field_errors()
+[]
+
+### SetPasswordForm:
+
+# The two new passwords do not match.
+
+>>> data = {
+...     'new_password1': 'abc123',
+...     'new_password2': 'abc',
+... }
+>>> form = SetPasswordForm(user, data)
+>>> form.is_valid()
+False
+>>> form["new_password2"].errors
+[u"The two password fields didn't match."]
+
+# The success case.
+
+>>> data = {
+...     'new_password1': 'abc123',
+...     'new_password2': 'abc123',
+... }
+>>> form = SetPasswordForm(user, data)
+>>> form.is_valid()
+True
+
+### PasswordChangeForm:
+
+The old password is incorrect.
+
+>>> data = {
+...     'old_password': 'test',
+...     'new_password1': 'abc123',
+...     'new_password2': 'abc123',
+... }
+>>> form = PasswordChangeForm(user, data)
+>>> form.is_valid()
+False
+>>> form["old_password"].errors
+[u'Your old password was entered incorrectly. Please enter it again.']
+
+# The two new passwords do not match.
+
+>>> data = {
+...     'old_password': 'test123',
+...     'new_password1': 'abc123',
+...     'new_password2': 'abc',
+... }
+>>> form = PasswordChangeForm(user, data)
+>>> form.is_valid()
+False
+>>> form["new_password2"].errors
+[u"The two password fields didn't match."]
+
+# The success case.
+
+>>> data = {
+...     'old_password': 'test123',
+...     'new_password1': 'abc123',
+...     'new_password2': 'abc123',
+... }
+>>> form = PasswordChangeForm(user, data)
+>>> form.is_valid()
+True
+
+# Regression test - check the order of fields:
+
+>>> PasswordChangeForm(user, {}).fields.keys()
+['old_password', 'new_password1', 'new_password2']
+
+### UserChangeForm
+
+>>> from mon_django.auth.forms import UserChangeForm
+>>> data = {'username': 'not valid'}
+>>> form = UserChangeForm(data, instance=user)
+>>> form.is_valid()
+False
+>>> form['username'].errors
+[u'This value may contain only letters, numbers and @/./+/-/_ characters.']
+
+
+### PasswordResetForm
+
+>>> from mon_django.auth.forms import PasswordResetForm
+>>> data = {'email':'not valid'}
+>>> form = PasswordResetForm(data)
+>>> form.is_valid()
+False
+>>> form['email'].errors
+[u'Enter a valid e-mail address.']
+
+# Test nonexistant email address
+>>> data = {'email':'foo@bar.com'}
+>>> form = PasswordResetForm(data)
+>>> form.is_valid()
+False
+>>> form.errors
+{'email': [u"That e-mail address doesn't have an associated user account. Are you sure you've registered?"]}
+
+# Test cleaned_data bug fix
+>>> user = User.objects.create_user("jsmith3", "jsmith3@example.com", "test123")
+>>> data = {'email':'jsmith3@example.com'}
+>>> form = PasswordResetForm(data)
+>>> form.is_valid()
+True
+>>> form.cleaned_data['email']
+u'jsmith3@example.com'
+
+# bug #5605, preserve the case of the user name (before the @ in the email address)
+# when creating a user.
+>>> user = User.objects.create_user('forms_test2', 'tesT@EXAMple.com', 'test')
+>>> user.email
+'tesT@example.com'
+>>> user = User.objects.create_user('forms_test3', 'tesT', 'test')
+>>> user.email
+'tesT'
+
+"""

File mon_django/auth/tests/models.py

+from django.conf import settings
+from django.test import TestCase
+from mon_django.auth.models import User, SiteProfileNotAvailable
+
+class ProfileTestCase(TestCase):
+    fixtures = ['authtestdata.json']
+    def setUp(self):
+        """Backs up the AUTH_PROFILE_MODULE"""
+        self.old_AUTH_PROFILE_MODULE = getattr(settings,
+                                               'AUTH_PROFILE_MODULE', None)
+
+    def tearDown(self):
+        """Restores the AUTH_PROFILE_MODULE -- if it was not set it is deleted,
+        otherwise the old value is restored"""
+        if self.old_AUTH_PROFILE_MODULE is None and \
+                hasattr(settings, 'AUTH_PROFILE_MODULE'):
+            del settings.AUTH_PROFILE_MODULE
+
+        if self.old_AUTH_PROFILE_MODULE is not None:
+            settings.AUTH_PROFILE_MODULE = self.old_AUTH_PROFILE_MODULE
+
+    def test_site_profile_not_available(self):
+        # calling get_profile without AUTH_PROFILE_MODULE set
+        if hasattr(settings, 'AUTH_PROFILE_MODULE'):
+            del settings.AUTH_PROFILE_MODULE
+        user = User.objects.get(username='testclient')
+        self.assertRaises(SiteProfileNotAvailable, user.get_profile)
+
+        # Bad syntax in AUTH_PROFILE_MODULE: 
+        settings.AUTH_PROFILE_MODULE = 'foobar'
+        self.assertRaises(SiteProfileNotAvailable, user.get_profile)
+
+        # module that doesn't exist
+        settings.AUTH_PROFILE_MODULE = 'foo.bar'
+        self.assertRaises(SiteProfileNotAvailable, user.get_profile)

File mon_django/auth/tests/remote_user.py

+from datetime import datetime
+
+from django.conf import settings
+from mon_django.auth.backends import RemoteUserBackend
+from mon_django.auth.models import User
+from django.test import TestCase
+
+
+class RemoteUserTest(TestCase):
+
+    urls = 'mon_django.auth.tests.urls'
+    middleware = 'mon_django.auth.middleware.RemoteUserMiddleware'
+    backend = 'mon_django.auth.backends.RemoteUserBackend'
+
+    # Usernames to be passed in REMOTE_USER for the test_known_user test case.
+    known_user = 'knownuser'
+    known_user2 = 'knownuser2'
+
+    def setUp(self):
+        self.curr_middleware = settings.MIDDLEWARE_CLASSES
+        self.curr_auth = settings.AUTHENTICATION_BACKENDS
+        settings.MIDDLEWARE_CLASSES += (self.middleware,)
+        settings.AUTHENTICATION_BACKENDS = (self.backend,)
+
+    def test_no_remote_user(self):
+        """
+        Tests requests where no remote user is specified and insures that no
+        users get created.
+        """
+        num_users = User.objects.count()
+
+        response = self.client.get('/remote_user/')
+        self.assert_(response.context['user'].is_anonymous())
+        self.assertEqual(User.objects.count(), num_users)
+
+        response = self.client.get('/remote_user/', REMOTE_USER=None)
+        self.assert_(response.context['user'].is_anonymous())
+        self.assertEqual(User.objects.count(), num_users)
+
+        response = self.client.get('/remote_user/', REMOTE_USER='')
+        self.assert_(response.context['user'].is_anonymous())
+        self.assertEqual(User.objects.count(), num_users)
+
+    def test_unknown_user(self):
+        """
+        Tests the case where the username passed in the header does not exist
+        as a User.
+        """
+        num_users = User.objects.count()
+        response = self.client.get('/remote_user/', REMOTE_USER='newuser')
+        self.assertEqual(response.context['user'].username, 'newuser')
+        self.assertEqual(User.objects.count(), num_users + 1)
+        User.objects.get(username='newuser')
+
+        # Another request with same user should not create any new users.
+        response = self.client.get('/remote_user/', REMOTE_USER='newuser')
+        self.assertEqual(User.objects.count(), num_users + 1)
+
+    def test_known_user(self):
+        """
+        Tests the case where the username passed in the header is a valid User.
+        """
+        User.objects.create(username='knownuser')
+        User.objects.create(username='knownuser2')
+        num_users = User.objects.count()
+        response = self.client.get('/remote_user/', REMOTE_USER=self.known_user)
+        self.assertEqual(response.context['user'].username, 'knownuser')
+        self.assertEqual(User.objects.count(), num_users)
+        # Test that a different user passed in the headers causes the new user
+        # to be logged in.
+        response = self.client.get('/remote_user/', REMOTE_USER=self.known_user2)
+        self.assertEqual(response.context['user'].username, 'knownuser2')
+        self.assertEqual(User.objects.count(), num_users)
+
+    def test_last_login(self):
+        """
+        Tests that a user's last_login is set the first time they make a
+        request but not updated in subsequent requests with the same session.
+        """
+        user = User.objects.create(username='knownuser')
+        # Set last_login to something so we can determine if it changes.
+        default_login = datetime(2000, 1, 1)
+        user.last_login = default_login
+        user.save()
+
+        response = self.client.get('/remote_user/', REMOTE_USER=self.known_user)
+        self.assertNotEqual(default_login, response.context['user'].last_login)
+
+        user = User.objects.get(username='knownuser')
+        user.last_login = default_login
+        user.save()
+        response = self.client.get('/remote_user/', REMOTE_USER=self.known_user)
+        self.assertEqual(default_login, response.context['user'].last_login)
+
+    def tearDown(self):
+        """Restores settings to avoid breaking other tests."""
+        settings.MIDDLEWARE_CLASSES = self.curr_middleware
+        settings.AUTHENTICATION_BACKENDS = self.curr_auth
+
+
+class RemoteUserNoCreateBackend(RemoteUserBackend):
+    """Backend that doesn't create unknown users."""
+    create_unknown_user = False
+
+
+class RemoteUserNoCreateTest(RemoteUserTest):
+    """
+    Contains the same tests as RemoteUserTest, but using a custom auth backend
+    class that doesn't create unknown users.
+    """
+
+    backend =\
+        'mon_django.auth.tests.remote_user.RemoteUserNoCreateBackend'
+
+    def test_unknown_user(self):
+        num_users = User.objects.count()
+        response = self.client.get('/remote_user/', REMOTE_USER='newuser')
+        self.assert_(response.context['user'].is_anonymous())
+        self.assertEqual(User.objects.count(), num_users)
+
+
+class CustomRemoteUserBackend(RemoteUserBackend):
+    """
+    Backend that overrides RemoteUserBackend methods.
+    """
+
+    def clean_username(self, username):
+        """
+        Grabs username before the @ character.
+        """
+        return username.split('@')[0]
+
+    def configure_user(self, user):
+        """
+        Sets user's email address.
+        """
+        user.email = 'user@example.com'
+        user.save()
+        return user
+
+
+class RemoteUserCustomTest(RemoteUserTest):
+    """
+    Tests a custom RemoteUserBackend subclass that overrides the clean_username
+    and configure_user methods.
+    """
+
+    backend =\
+        'mon_django.auth.tests.remote_user.CustomRemoteUserBackend'
+    # REMOTE_USER strings with e-mail addresses for the custom backend to
+    # clean.
+    known_user = 'knownuser@example.com'
+    known_user2 = 'knownuser2@example.com'
+
+    def test_known_user(self):
+        """
+        The strings passed in REMOTE_USER should be cleaned and the known users
+        should not have been configured with an email address.
+        """
+        super(RemoteUserCustomTest, self).test_known_user()
+        self.assertEqual(User.objects.get(username='knownuser').email, '')
+        self.assertEqual(User.objects.get(username='knownuser2').email, '')
+
+    def test_unknown_user(self):
+        """
+        The unknown user created should be configured with an email address.
+        """
+        super(RemoteUserCustomTest, self).test_unknown_user()
+        newuser = User.objects.get(username='newuser')
+        self.assertEqual(newuser.email, 'user@example.com')

File mon_django/auth/tests/templates/registration/login.html

+{{ form.as_ul }}

File mon_django/auth/tests/templates/registration/password_reset_complete.html

+Password reset successfully

File mon_django/auth/tests/templates/registration/password_reset_confirm.html

+{% if validlink %}
+Please enter your new password: {{ form }}
+{% else %}
+The password reset link was invalid
+{% endif %}

File mon_django/auth/tests/templates/registration/password_reset_done.html

+E-mail sent

File mon_django/auth/tests/templates/registration/password_reset_email.html

+{{ protocol }}://{{ domain }}/reset/{{ uid }}-{{ token }}/

File mon_django/auth/tests/templates/registration/password_reset_form.html

+{{ form }}

File mon_django/auth/tests/tokens.py

+TOKEN_GENERATOR_TESTS = """
+>>> from mon_django.auth.models import User, AnonymousUser
+>>> from mon_django.auth.tokens import PasswordResetTokenGenerator
+>>> from django.conf import settings
+>>> u = User.objects.create_user('tokentestuser', 'test2@example.com', 'testpw')
+>>> p0 = PasswordResetTokenGenerator()
+>>> tk1 = p0.make_token(u)
+>>> p0.check_token(u, tk1)
+True
+
+>>> u = User.objects.create_user('comebackkid', 'test3@example.com', 'testpw')
+>>> p0 = PasswordResetTokenGenerator()
+>>> tk1 = p0.make_token(u)
+>>> reload = User.objects.get(username='comebackkid')
+>>> tk2 = p0.make_token(reload)
+>>> tk1 == tk2
+True
+
+Tests to ensure we can use the token after n days, but no greater.
+Use a mocked version of PasswordResetTokenGenerator so we can change
+the value of 'today'
+
+>>> class Mocked(PasswordResetTokenGenerator):
+...     def __init__(self, today):
+...         self._today_val = today
+...     def _today(self):
+...         return self._today_val
+
+>>> from datetime import date, timedelta
+>>> p1 = Mocked(date.today() + timedelta(settings.PASSWORD_RESET_TIMEOUT_DAYS))
+>>> p1.check_token(u, tk1)
+True
+>>> p2 = Mocked(date.today() + timedelta(settings.PASSWORD_RESET_TIMEOUT_DAYS + 1))
+>>> p2.check_token(u, tk1)
+False
+
+"""

File mon_django/auth/tests/urls.py

+from django.conf.urls.defaults import patterns
+from mon_django.auth.urls import urlpatterns
+from django.http import HttpResponse
+from django.template import Template, RequestContext
+
+def remote_user_auth_view(request):
+    "Dummy view for remote user tests"
+    t = Template("Username is {{ user }}.")
+    c = RequestContext(request, {})
+    return HttpResponse(t.render(c))
+
+# special urls for auth test cases
+urlpatterns += patterns('',
+    (r'^logout/custom_query/$', 'mon_django.auth.views.logout', dict(redirect_field_name='follow')),
+    (r'^logout/next_page/$', 'mon_django.auth.views.logout', dict(next_page='/somewhere/')),
+    (r'^remote_user/$', remote_user_auth_view),
+)
+

File mon_django/auth/tests/views.py

+import os
+import re
+import urllib
+
+from django.conf import settings
+from mon_django.auth import SESSION_KEY, REDIRECT_FIELD_NAME
+from mon_django.auth.forms import AuthenticationForm
+from django.contrib.sites.models import Site, RequestSite
+from mon_django.auth.models import User
+from django.test import TestCase
+from django.core import mail
+from django.core.urlresolvers import reverse
+
+class AuthViewsTestCase(TestCase):
+    """
+    Helper base class for all the follow test cases.
+    """
+    fixtures = ['authtestdata.json']
+    urls = 'mon_django.auth.urls'
+
+    def setUp(self):
+        self.old_LANGUAGES = settings.LANGUAGES
+        self.old_LANGUAGE_CODE = settings.LANGUAGE_CODE
+        settings.LANGUAGES = (('en', 'English'),)
+        settings.LANGUAGE_CODE = 'en'
+        self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
+        settings.TEMPLATE_DIRS = (
+            os.path.join(
+                os.path.dirname(__file__),
+                'templates'
+            )
+        ,)
+
+    def tearDown(self):
+        settings.LANGUAGES = self.old_LANGUAGES
+        settings.LANGUAGE_CODE = self.old_LANGUAGE_CODE
+        settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS
+
+class PasswordResetTest(AuthViewsTestCase):
+
+    def test_email_not_found(self):
+        "Error is raised if the provided email address isn't currently registered"
+        response = self.client.get('/password_reset/')
+        self.assertEquals(response.status_code, 200)
+        response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'})
+        self.assertContains(response, "That e-mail address doesn&#39;t have an associated user account")
+        self.assertEquals(len(mail.outbox), 0)
+
+    def test_email_found(self):
+        "Email is sent if a valid email address is provided for password reset"
+        response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
+        self.assertEquals(response.status_code, 302)
+        self.assertEquals(len(mail.outbox), 1)
+        self.assert_("http://" in mail.outbox[0].body)
+
+    def _test_confirm_start(self):
+        # Start by creating the email
+        response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
+        self.assertEquals(response.status_code, 302)
+        self.assertEquals(len(mail.outbox), 1)
+        return self._read_signup_email(mail.outbox[0])
+
+    def _read_signup_email(self, email):
+        urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
+        self.assert_(urlmatch is not None, "No URL found in sent email")
+        return urlmatch.group(), urlmatch.groups()[0]
+
+    def test_confirm_valid(self):
+        url, path = self._test_confirm_start()
+        response = self.client.get(path)
+        # redirect to a 'complete' page:
+        self.assertEquals(response.status_code, 200)
+        self.assert_("Please enter your new password" in response.content)
+
+    def test_confirm_invalid(self):
+        url, path = self._test_confirm_start()
+        # Let's munge the token in the path, but keep the same length,
+        # in case the URLconf will reject a different length.
+        path = path[:-5] + ("0"*4) + path[-1]
+
+        response = self.client.get(path)
+        self.assertEquals(response.status_code, 200)
+        self.assert_("The password reset link was invalid" in response.content)
+
+    def test_confirm_invalid_post(self):
+        # Same as test_confirm_invalid, but trying
+        # to do a POST instead.
+        url, path = self._test_confirm_start()
+        path = path[:-5] + ("0"*4) + path[-1]
+
+        response = self.client.post(path, {'new_password1': 'anewpassword',
+                                           'new_password2':' anewpassword'})
+        # Check the password has not been changed
+        u = User.objects.get(email='staffmember@example.com')
+        self.assert_(not u.check_password("anewpassword"))
+
+    def test_confirm_complete(self):
+        url, path = self._test_confirm_start()
+        response = self.client.post(path, {'new_password1': 'anewpassword',
+                                           'new_password2': 'anewpassword'})
+        # It redirects us to a 'complete' page:
+        self.assertEquals(response.status_code, 302)
+        # Check the password has been changed
+        u = User.objects.get(email='staffmember@example.com')
+        self.assert_(u.check_password("anewpassword"))
+
+        # Check we can't use the link again
+        response = self.client.get(path)
+        self.assertEquals(response.status_code, 200)
+        self.assert_("The password reset link was invalid" in response.content)
+
+    def test_confirm_different_passwords(self):
+        url, path = self._test_confirm_start()
+        response = self.client.post(path, {'new_password1': 'anewpassword',
+                                           'new_password2':' x'})
+        self.assertEquals(response.status_code, 200)
+        self.assert_("The two password fields didn&#39;t match" in response.content)
+
+class ChangePasswordTest(AuthViewsTestCase):
+
+    def login(self, password='password'):
+        response = self.client.post('/login/', {
+            'username': 'testclient',
+            'password': password
+            }
+        )
+        self.assertEquals(response.status_code, 302)
+        self.assert_(response['Location'].endswith(settings.LOGIN_REDIRECT_URL))
+
+    def fail_login(self, password='password'):
+        response = self.client.post('/login/', {
+            'username': 'testclient',
+            'password': password
+            }
+        )
+        self.assertEquals(response.status_code, 200)
+        self.assert_("Please enter a correct username and password. Note that both fields are case-sensitive." in response.content)
+
+    def logout(self):
+        response = self.client.get('/logout/')
+
+    def test_password_change_fails_with_invalid_old_password(self):
+        self.login()
+        response = self.client.post('/password_change/', {
+            'old_password': 'donuts',
+            'new_password1': 'password1',
+            'new_password2': 'password1',
+            }
+        )
+        self.assertEquals(response.status_code, 200)
+        self.assert_("Your old password was entered incorrectly. Please enter it again." in response.content)
+
+    def test_password_change_fails_with_mismatched_passwords(self):
+        self.login()
+        response = self.client.post('/password_change/', {
+            'old_password': 'password',