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