Merge branch 'gilbert-ext4-murano' of git://github.com/lapilofu/philo into gilbert...
[philo.git] / philo / 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 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
10
11
12 class EmailInput(forms.TextInput):
13         input_type = 'email'
14
15
16 class RegistrationForm(UserCreationForm):
17         email = forms.EmailField(widget=EmailInput)
18         try:
19                 from recaptcha_django import ReCaptchaField
20         except ImportError:
21                 pass
22         else:
23                 if 'recaptcha_django.middleware.ReCaptchaMiddleware' in settings.MIDDLEWARE_CLASSES:
24                         recaptcha = ReCaptchaField()
25         
26         def clean_username(self):
27                 username = self.cleaned_data['username']
28                 
29                 # Trivial case: if the username doesn't exist, go for it!
30                 try:
31                         user = User.objects.get(username=username)
32                 except User.DoesNotExist:
33                         return username
34                 
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.
37                         user.delete()
38                         return username
39                 
40                 raise ValidationError(_("A user with that username already exists."))
41         
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']
46         
47         def save(self):
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
53                 new_user.save()
54                 return new_user
55
56
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)
61         
62         def __init__(self, user, *args, **kwargs):
63                 kwargs['instance'] = user
64                 super(UserAccountForm, self).__init__(*args, **kwargs)
65         
66         class Meta:
67                 model = User
68                 fields = ('first_name', 'last_name', 'email')
69
70
71 class WaldoAuthenticationForm(AuthenticationForm):
72         ERROR_MESSAGE = _("Please enter a correct username and password. Note that both fields are case-sensitive.")
73         
74         def clean(self):
75                 username = self.cleaned_data.get('username')
76                 password = self.cleaned_data.get('password')
77                 message = self.ERROR_MESSAGE
78                 
79                 if username and password:
80                         self.user_cache = authenticate(username=username, password=password)
81                         if self.user_cache is None:
82                                 if u'@' in username:
83                                         # Maybe they entered their email? Look it up, but still raise a ValidationError.
84                                         try:
85                                                 user = User.objects.get(email=username)
86                                         except (User.DoesNotExist, User.MultipleObjectsReturned):
87                                                 pass
88                                         else:
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
96         
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."))