|
1 from django.contrib.auth.models import User |
|
2 from django.contrib.auth import authenticate |
|
3 from django.contrib.auth.tokens import default_token_generator |
|
4 from django.contrib.sites.models import Site |
|
5 from django.template import Context, loader |
|
6 from django import forms |
|
7 from django.utils.translation import ugettext_lazy as _ |
|
8 from django.utils.http import int_to_base36 |
|
9 |
|
10 class UserCreationForm(forms.ModelForm): |
|
11 """ |
|
12 A form that creates a user, with no privileges, from the given username and password. |
|
13 """ |
|
14 username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$', |
|
15 help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."), |
|
16 error_message = _("This value must contain only letters, numbers and underscores.")) |
|
17 password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) |
|
18 password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput) |
|
19 |
|
20 class Meta: |
|
21 model = User |
|
22 fields = ("username",) |
|
23 |
|
24 def clean_username(self): |
|
25 username = self.cleaned_data["username"] |
|
26 try: |
|
27 User.objects.get(username=username) |
|
28 except User.DoesNotExist: |
|
29 return username |
|
30 raise forms.ValidationError(_("A user with that username already exists.")) |
|
31 |
|
32 def clean_password2(self): |
|
33 password1 = self.cleaned_data.get("password1", "") |
|
34 password2 = self.cleaned_data["password2"] |
|
35 if password1 != password2: |
|
36 raise forms.ValidationError(_("The two password fields didn't match.")) |
|
37 return password2 |
|
38 |
|
39 def save(self, commit=True): |
|
40 user = super(UserCreationForm, self).save(commit=False) |
|
41 user.set_password(self.cleaned_data["password1"]) |
|
42 if commit: |
|
43 user.save() |
|
44 return user |
|
45 |
|
46 class UserChangeForm(forms.ModelForm): |
|
47 username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$', |
|
48 help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."), |
|
49 error_message = _("This value must contain only letters, numbers and underscores.")) |
|
50 |
|
51 class Meta: |
|
52 model = User |
|
53 |
|
54 class AuthenticationForm(forms.Form): |
|
55 """ |
|
56 Base class for authenticating users. Extend this to get a form that accepts |
|
57 username/password logins. |
|
58 """ |
|
59 username = forms.CharField(label=_("Username"), max_length=30) |
|
60 password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) |
|
61 |
|
62 def __init__(self, request=None, *args, **kwargs): |
|
63 """ |
|
64 If request is passed in, the form will validate that cookies are |
|
65 enabled. Note that the request (a HttpRequest object) must have set a |
|
66 cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before |
|
67 running this validation. |
|
68 """ |
|
69 self.request = request |
|
70 self.user_cache = None |
|
71 super(AuthenticationForm, self).__init__(*args, **kwargs) |
|
72 |
|
73 def clean(self): |
|
74 username = self.cleaned_data.get('username') |
|
75 password = self.cleaned_data.get('password') |
|
76 |
|
77 if username and password: |
|
78 self.user_cache = authenticate(username=username, password=password) |
|
79 if self.user_cache is None: |
|
80 raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive.")) |
|
81 elif not self.user_cache.is_active: |
|
82 raise forms.ValidationError(_("This account is inactive.")) |
|
83 |
|
84 # TODO: determine whether this should move to its own method. |
|
85 if self.request: |
|
86 if not self.request.session.test_cookie_worked(): |
|
87 raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.")) |
|
88 |
|
89 return self.cleaned_data |
|
90 |
|
91 def get_user_id(self): |
|
92 if self.user_cache: |
|
93 return self.user_cache.id |
|
94 return None |
|
95 |
|
96 def get_user(self): |
|
97 return self.user_cache |
|
98 |
|
99 class PasswordResetForm(forms.Form): |
|
100 email = forms.EmailField(label=_("E-mail"), max_length=75) |
|
101 |
|
102 def clean_email(self): |
|
103 """ |
|
104 Validates that a user exists with the given e-mail address. |
|
105 """ |
|
106 email = self.cleaned_data["email"] |
|
107 self.users_cache = User.objects.filter(email__iexact=email) |
|
108 if len(self.users_cache) == 0: |
|
109 raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?")) |
|
110 return email |
|
111 |
|
112 def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', |
|
113 use_https=False, token_generator=default_token_generator): |
|
114 """ |
|
115 Generates a one-use only link for resetting password and sends to the user |
|
116 """ |
|
117 from django.core.mail import send_mail |
|
118 for user in self.users_cache: |
|
119 if not domain_override: |
|
120 current_site = Site.objects.get_current() |
|
121 site_name = current_site.name |
|
122 domain = current_site.domain |
|
123 else: |
|
124 site_name = domain = domain_override |
|
125 t = loader.get_template(email_template_name) |
|
126 c = { |
|
127 'email': user.email, |
|
128 'domain': domain, |
|
129 'site_name': site_name, |
|
130 'uid': int_to_base36(user.id), |
|
131 'user': user, |
|
132 'token': token_generator.make_token(user), |
|
133 'protocol': use_https and 'https' or 'http', |
|
134 } |
|
135 send_mail(_("Password reset on %s") % site_name, |
|
136 t.render(Context(c)), None, [user.email]) |
|
137 |
|
138 class SetPasswordForm(forms.Form): |
|
139 """ |
|
140 A form that lets a user change set his/her password without |
|
141 entering the old password |
|
142 """ |
|
143 new_password1 = forms.CharField(label=_("New password"), widget=forms.PasswordInput) |
|
144 new_password2 = forms.CharField(label=_("New password confirmation"), widget=forms.PasswordInput) |
|
145 |
|
146 def __init__(self, user, *args, **kwargs): |
|
147 self.user = user |
|
148 super(SetPasswordForm, self).__init__(*args, **kwargs) |
|
149 |
|
150 def clean_new_password2(self): |
|
151 password1 = self.cleaned_data.get('new_password1') |
|
152 password2 = self.cleaned_data.get('new_password2') |
|
153 if password1 and password2: |
|
154 if password1 != password2: |
|
155 raise forms.ValidationError(_("The two password fields didn't match.")) |
|
156 return password2 |
|
157 |
|
158 def save(self, commit=True): |
|
159 self.user.set_password(self.cleaned_data['new_password1']) |
|
160 if commit: |
|
161 self.user.save() |
|
162 return self.user |
|
163 |
|
164 class PasswordChangeForm(SetPasswordForm): |
|
165 """ |
|
166 A form that lets a user change his/her password by entering |
|
167 their old password. |
|
168 """ |
|
169 old_password = forms.CharField(label=_("Old password"), widget=forms.PasswordInput) |
|
170 |
|
171 def clean_old_password(self): |
|
172 """ |
|
173 Validates that the old_password field is correct. |
|
174 """ |
|
175 old_password = self.cleaned_data["old_password"] |
|
176 if not self.user.check_password(old_password): |
|
177 raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again.")) |
|
178 return old_password |
|
179 PasswordChangeForm.base_fields.keyOrder = ['old_password', 'new_password1', 'new_password2'] |
|
180 |
|
181 class AdminPasswordChangeForm(forms.Form): |
|
182 """ |
|
183 A form used to change the password of a user in the admin interface. |
|
184 """ |
|
185 password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput) |
|
186 password2 = forms.CharField(label=_("Password (again)"), widget=forms.PasswordInput) |
|
187 |
|
188 def __init__(self, user, *args, **kwargs): |
|
189 self.user = user |
|
190 super(AdminPasswordChangeForm, self).__init__(*args, **kwargs) |
|
191 |
|
192 def clean_password2(self): |
|
193 password1 = self.cleaned_data.get('password1') |
|
194 password2 = self.cleaned_data.get('password2') |
|
195 if password1 and password2: |
|
196 if password1 != password2: |
|
197 raise forms.ValidationError(_("The two password fields didn't match.")) |
|
198 return password2 |
|
199 |
|
200 def save(self, commit=True): |
|
201 """ |
|
202 Saves the new password. |
|
203 """ |
|
204 self.user.set_password(self.cleaned_data["password1"]) |
|
205 if commit: |
|
206 self.user.save() |
|
207 return self.user |