1 from datetime import date
2 from django import forms
3 from django.conf import settings
4 from django.contrib.auth import authenticate
5 from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
6 from django.contrib.auth.models import User
7 from django.core.exceptions import ValidationError
8 from django.utils.translation import ugettext_lazy as _
9 from philo.contrib.waldo.tokens import REGISTRATION_TIMEOUT_DAYS
12 class EmailInput(forms.TextInput):
16 class RegistrationForm(UserCreationForm):
17 email = forms.EmailField(widget=EmailInput)
19 from recaptcha_django import ReCaptchaField
23 if 'recaptcha_django.middleware.ReCaptchaMiddleware' in settings.MIDDLEWARE_CLASSES:
24 recaptcha = ReCaptchaField()
26 def clean_username(self):
27 username = self.cleaned_data['username']
29 # Trivial case: if the username doesn't exist, go for it!
31 user = User.objects.get(username=username)
32 except User.DoesNotExist:
35 if not user.is_active and (date.today() - user.date_joined.date()).days > REGISTRATION_TIMEOUT_DAYS and user.last_login == user.date_joined:
36 # Then this is a user who has not confirmed their registration and whose time is up. Delete the old user and return the username.
40 raise ValidationError(_("A user with that username already exists."))
42 def clean_email(self):
43 if User.objects.filter(email__iexact=self.cleaned_data['email']):
44 raise ValidationError(_('This email is already in use. Please supply a different email address'))
45 return self.cleaned_data['email']
48 username = self.cleaned_data['username']
49 email = self.cleaned_data['email']
50 password = self.cleaned_data['password1']
51 new_user = User.objects.create_user(username, email, password)
52 new_user.is_active = False
57 class UserAccountForm(forms.ModelForm):
58 first_name = User._meta.get_field('first_name').formfield(required=True)
59 last_name = User._meta.get_field('last_name').formfield(required=True)
60 email = User._meta.get_field('email').formfield(required=True, widget=EmailInput)
62 def __init__(self, user, *args, **kwargs):
63 kwargs['instance'] = user
64 super(UserAccountForm, self).__init__(*args, **kwargs)
68 fields = ('first_name', 'last_name', 'email')
71 class WaldoAuthenticationForm(AuthenticationForm):
72 ERROR_MESSAGE = _("Please enter a correct username and password. Note that both fields are case-sensitive.")
75 username = self.cleaned_data.get('username')
76 password = self.cleaned_data.get('password')
77 message = self.ERROR_MESSAGE
79 if username and password:
80 self.user_cache = authenticate(username=username, password=password)
81 if self.user_cache is None:
83 # Maybe they entered their email? Look it up, but still raise a ValidationError.
85 user = User.objects.get(email=username)
86 except (User.DoesNotExist, User.MultipleObjectsReturned):
89 if user.check_password(password):
90 message = _("Your e-mail address is not your username. Try '%s' instead.") % user.username
91 raise ValidationError(message)
92 elif not self.user_cache.is_active:
93 raise ValidationError(message)
94 self.check_for_test_cookie()
95 return self.cleaned_data
97 def check_for_test_cookie(self):
98 # This method duplicates the Django 1.3 AuthenticationForm method.
99 if self.request and not self.request.session.test_cookie_worked():
100 raise forms.ValidationError(
101 _("Your Web browser doesn't appear to have cookies enabled. "
102 "Cookies are required for logging in."))