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