Merge branch 'master' of git://github.com/melinath/philo
[philo.git] / contrib / waldo / forms.py
1 from datetime import date
2 from django import forms
3 from django.conf import settings
4 from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
5 from django.contrib.auth.models import User
6 from django.core.exceptions import ValidationError
7 from django.utils.translation import ugettext_lazy as _
8 from philo.contrib.waldo.tokens import REGISTRATION_TIMEOUT_DAYS
9
10
11 LOGIN_FORM_KEY = 'this_is_the_login_form'
12 LoginForm = type('LoginForm', (AuthenticationForm,), {
13         LOGIN_FORM_KEY: forms.BooleanField(widget=forms.HiddenInput, initial=True)
14 })
15
16
17 class EmailInput(forms.TextInput):
18         input_type = 'email'
19
20
21 class RegistrationForm(UserCreationForm):
22         email = forms.EmailField(widget=EmailInput)
23         try:
24                 from recaptcha_django import ReCaptchaField
25         except ImportError:
26                 pass
27         else:
28                 if 'recaptcha_django.middleware.ReCaptchaMiddleware' in settings.MIDDLEWARE_CLASSES:
29                         recaptcha = ReCaptchaField()
30         
31         def clean_username(self):
32                 username = self.cleaned_data['username']
33                 
34                 # Trivial case: if the username doesn't exist, go for it!
35                 try:
36                         user = User.objects.get(username=username)
37                 except User.DoesNotExist:
38                         return username
39                 
40                 if not user.is_active and (date.today() - user.date_joined.date()).days > REGISTRATION_TIMEOUT_DAYS and user.last_login == user.date_joined:
41                         # Then this is a user who has not confirmed their registration and whose time is up. Delete the old user and return the username.
42                         user.delete()
43                         return username
44                 
45                 raise ValidationError(_("A user with that username already exists."))
46         
47         def clean_email(self):
48                 if User.objects.filter(email__iexact=self.cleaned_data['email']):
49                         raise ValidationError(_('This email is already in use. Please supply a different email address'))
50                 return self.cleaned_data['email']
51         
52         def save(self):
53                 username = self.cleaned_data['username']
54                 email = self.cleaned_data['email']
55                 password = self.cleaned_data['password1']
56                 new_user = User.objects.create_user(username, email, password)
57                 new_user.is_active = False
58                 new_user.save()
59                 return new_user