root / snf-astakos-app / astakos / im / forms.py @ 0a569195
History | View | Annotate | Download (17.4 kB)
1 |
# Copyright 2011-2012 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
from urlparse import urljoin |
34 |
from datetime import datetime |
35 |
|
36 |
from django import forms |
37 |
from django.utils.translation import ugettext as _ |
38 |
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, PasswordResetForm |
39 |
from django.core.mail import send_mail |
40 |
from django.contrib.auth.tokens import default_token_generator |
41 |
from django.template import Context, loader |
42 |
from django.utils.http import int_to_base36 |
43 |
from django.core.urlresolvers import reverse |
44 |
from django.utils.functional import lazy |
45 |
from django.utils.safestring import mark_safe |
46 |
from django.contrib import messages |
47 |
|
48 |
from astakos.im.models import AstakosUser, Invitation |
49 |
from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL, RECAPTCHA_ENABLED |
50 |
from astakos.im.widgets import DummyWidget, RecaptchaWidget, ApprovalTermsWidget |
51 |
|
52 |
# since Django 1.4 use django.core.urlresolvers.reverse_lazy instead
|
53 |
from astakos.im.util import reverse_lazy, get_latest_terms, reserved_email, get_query |
54 |
|
55 |
import logging |
56 |
import recaptcha.client.captcha as captcha |
57 |
|
58 |
logger = logging.getLogger(__name__) |
59 |
|
60 |
class LocalUserCreationForm(UserCreationForm): |
61 |
"""
|
62 |
Extends the built in UserCreationForm in several ways:
|
63 |
|
64 |
* Adds email, first_name, last_name, recaptcha_challenge_field, recaptcha_response_field field.
|
65 |
* The username field isn't visible and it is assigned a generated id.
|
66 |
* User created is not active.
|
67 |
"""
|
68 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
69 |
recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
|
70 |
|
71 |
class Meta: |
72 |
model = AstakosUser |
73 |
fields = ("email", "first_name", "last_name", "has_signed_terms") |
74 |
widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))} |
75 |
|
76 |
def __init__(self, *args, **kwargs): |
77 |
"""
|
78 |
Changes the order of fields, and removes the username field.
|
79 |
"""
|
80 |
request = kwargs.get('request', None) |
81 |
if request:
|
82 |
kwargs.pop('request')
|
83 |
self.ip = request.META.get('REMOTE_ADDR', |
84 |
request.META.get('HTTP_X_REAL_IP', None)) |
85 |
|
86 |
super(LocalUserCreationForm, self).__init__(*args, **kwargs) |
87 |
self.fields.keyOrder = ['email', 'first_name', 'last_name', |
88 |
'password1', 'password2'] |
89 |
if get_latest_terms():
|
90 |
self.fields.keyOrder.append('has_signed_terms') |
91 |
if RECAPTCHA_ENABLED:
|
92 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
93 |
'recaptcha_response_field',])
|
94 |
|
95 |
if 'has_signed_terms' in self.fields: |
96 |
# Overriding field label since we need to apply a link
|
97 |
# to the terms within the label
|
98 |
terms_link_html = '<a href="%s" target="_blank">%s</a>' \
|
99 |
% (reverse('latest_terms'), _("the terms")) |
100 |
self.fields['has_signed_terms'].label = \ |
101 |
mark_safe("I agree with %s" % terms_link_html)
|
102 |
|
103 |
def clean_email(self): |
104 |
email = self.cleaned_data['email'] |
105 |
if not email: |
106 |
raise forms.ValidationError(_("This field is required")) |
107 |
if reserved_email(email):
|
108 |
raise forms.ValidationError(_("This email is already used")) |
109 |
return email
|
110 |
|
111 |
def clean_has_signed_terms(self): |
112 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
113 |
if not has_signed_terms: |
114 |
raise forms.ValidationError(_('You have to agree with the terms')) |
115 |
return has_signed_terms
|
116 |
|
117 |
def clean_recaptcha_response_field(self): |
118 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
119 |
self.validate_captcha()
|
120 |
return self.cleaned_data['recaptcha_response_field'] |
121 |
|
122 |
def clean_recaptcha_challenge_field(self): |
123 |
if 'recaptcha_response_field' in self.cleaned_data: |
124 |
self.validate_captcha()
|
125 |
return self.cleaned_data['recaptcha_challenge_field'] |
126 |
|
127 |
def validate_captcha(self): |
128 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
129 |
rrf = self.cleaned_data['recaptcha_response_field'] |
130 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
131 |
if not check.is_valid: |
132 |
raise forms.ValidationError(_('You have not entered the correct words')) |
133 |
|
134 |
def save(self, commit=True): |
135 |
"""
|
136 |
Saves the email, first_name and last_name properties, after the normal
|
137 |
save behavior is complete.
|
138 |
"""
|
139 |
user = super(LocalUserCreationForm, self).save(commit=False) |
140 |
user.renew_token() |
141 |
if commit:
|
142 |
user.save() |
143 |
logger.info('Created user %s', user)
|
144 |
return user
|
145 |
|
146 |
class InvitedLocalUserCreationForm(LocalUserCreationForm): |
147 |
"""
|
148 |
Extends the LocalUserCreationForm: adds an inviter readonly field.
|
149 |
"""
|
150 |
|
151 |
inviter = forms.CharField(widget=forms.TextInput(), label=_('Inviter Real Name'))
|
152 |
|
153 |
class Meta: |
154 |
model = AstakosUser |
155 |
fields = ("email", "first_name", "last_name", "has_signed_terms") |
156 |
widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))} |
157 |
|
158 |
def __init__(self, *args, **kwargs): |
159 |
"""
|
160 |
Changes the order of fields, and removes the username field.
|
161 |
"""
|
162 |
super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs) |
163 |
|
164 |
#set readonly form fields
|
165 |
ro = ('inviter', 'email', 'username',) |
166 |
for f in ro: |
167 |
self.fields[f].widget.attrs['readonly'] = True |
168 |
|
169 |
|
170 |
def save(self, commit=True): |
171 |
user = super(InvitedLocalUserCreationForm, self).save(commit=False) |
172 |
level = user.invitation.inviter.level + 1
|
173 |
user.level = level |
174 |
user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
|
175 |
user.email_verified = True
|
176 |
if commit:
|
177 |
user.save() |
178 |
return user
|
179 |
|
180 |
class ThirdPartyUserCreationForm(forms.ModelForm): |
181 |
class Meta: |
182 |
model = AstakosUser |
183 |
fields = ("email", "first_name", "last_name", "third_party_identifier") |
184 |
widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))} |
185 |
|
186 |
def __init__(self, *args, **kwargs): |
187 |
"""
|
188 |
Changes the order of fields, and removes the username field.
|
189 |
"""
|
190 |
self.request = kwargs.get('request', None) |
191 |
if self.request: |
192 |
kwargs.pop('request')
|
193 |
super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs) |
194 |
self.fields.keyOrder = ['email', 'first_name', 'last_name', 'third_party_identifier'] |
195 |
if get_latest_terms():
|
196 |
self.fields.keyOrder.append('has_signed_terms') |
197 |
#set readonly form fields
|
198 |
ro = ["third_party_identifier", "first_name", "last_name"] |
199 |
for f in ro: |
200 |
self.fields[f].widget.attrs['readonly'] = True |
201 |
|
202 |
if 'has_signed_terms' in self.fields: |
203 |
# Overriding field label since we need to apply a link
|
204 |
# to the terms within the label
|
205 |
terms_link_html = '<a href="%s" target="_blank">%s</a>' \
|
206 |
% (reverse('latest_terms'), _("the terms")) |
207 |
self.fields['has_signed_terms'].label = \ |
208 |
mark_safe("I agree with %s" % terms_link_html)
|
209 |
|
210 |
def clean_email(self): |
211 |
email = self.cleaned_data['email'] |
212 |
if not email: |
213 |
raise forms.ValidationError(_("This field is required")) |
214 |
if reserved_email(email):
|
215 |
raise forms.ValidationError(_("This email is already used")) |
216 |
return email
|
217 |
|
218 |
def clean_has_signed_terms(self): |
219 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
220 |
if not has_signed_terms: |
221 |
raise forms.ValidationError(_('You have to agree with the terms')) |
222 |
return has_signed_terms
|
223 |
|
224 |
def save(self, commit=True): |
225 |
user = super(ThirdPartyUserCreationForm, self).save(commit=False) |
226 |
user.set_unusable_password() |
227 |
user.renew_token() |
228 |
user.provider = get_query(self.request).get('provider') |
229 |
if commit:
|
230 |
user.save() |
231 |
logger.info('Created user %s', user)
|
232 |
return user
|
233 |
|
234 |
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm): |
235 |
"""
|
236 |
Extends the LocalUserCreationForm: adds an inviter readonly field.
|
237 |
"""
|
238 |
inviter = forms.CharField(widget=forms.TextInput(), label=_('Inviter Real Name'))
|
239 |
|
240 |
def __init__(self, *args, **kwargs): |
241 |
"""
|
242 |
Changes the order of fields, and removes the username field.
|
243 |
"""
|
244 |
super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs) |
245 |
|
246 |
#set readonly form fields
|
247 |
ro = ('inviter', 'email',) |
248 |
for f in ro: |
249 |
self.fields[f].widget.attrs['readonly'] = True |
250 |
|
251 |
def save(self, commit=True): |
252 |
user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False) |
253 |
level = user.invitation.inviter.level + 1
|
254 |
user.level = level |
255 |
user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
|
256 |
user.email_verified = True
|
257 |
if commit:
|
258 |
user.save() |
259 |
return user
|
260 |
|
261 |
class ShibbolethUserCreationForm(ThirdPartyUserCreationForm): |
262 |
def clean_email(self): |
263 |
email = self.cleaned_data['email'] |
264 |
if not email: |
265 |
raise forms.ValidationError(_("This field is required")) |
266 |
for user in AstakosUser.objects.filter(email = email): |
267 |
if user.provider == 'shibboleth': |
268 |
raise forms.ValidationError(_("This email is already associated with another shibboleth account.")) |
269 |
return email
|
270 |
|
271 |
class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, InvitedThirdPartyUserCreationForm): |
272 |
pass
|
273 |
|
274 |
class LoginForm(AuthenticationForm): |
275 |
username = forms.EmailField(label=_("Email"))
|
276 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
277 |
recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
|
278 |
|
279 |
def __init__(self, *args, **kwargs): |
280 |
was_limited = kwargs.get('was_limited', False) |
281 |
request = kwargs.get('request', None) |
282 |
if request:
|
283 |
self.ip = request.META.get('REMOTE_ADDR', |
284 |
request.META.get('HTTP_X_REAL_IP', None)) |
285 |
|
286 |
t = ('request', 'was_limited') |
287 |
for elem in t: |
288 |
if elem in kwargs.keys(): |
289 |
kwargs.pop(elem) |
290 |
super(LoginForm, self).__init__(*args, **kwargs) |
291 |
|
292 |
self.fields.keyOrder = ['username', 'password'] |
293 |
if was_limited and RECAPTCHA_ENABLED: |
294 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
295 |
'recaptcha_response_field',])
|
296 |
|
297 |
def clean_recaptcha_response_field(self): |
298 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
299 |
self.validate_captcha()
|
300 |
return self.cleaned_data['recaptcha_response_field'] |
301 |
|
302 |
def clean_recaptcha_challenge_field(self): |
303 |
if 'recaptcha_response_field' in self.cleaned_data: |
304 |
self.validate_captcha()
|
305 |
return self.cleaned_data['recaptcha_challenge_field'] |
306 |
|
307 |
def validate_captcha(self): |
308 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
309 |
rrf = self.cleaned_data['recaptcha_response_field'] |
310 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
311 |
if not check.is_valid: |
312 |
raise forms.ValidationError(_('You have not entered the correct words')) |
313 |
|
314 |
class ProfileForm(forms.ModelForm): |
315 |
"""
|
316 |
Subclass of ``ModelForm`` for permiting user to edit his/her profile.
|
317 |
Most of the fields are readonly since the user is not allowed to change them.
|
318 |
|
319 |
The class defines a save method which sets ``is_verified`` to True so as the user
|
320 |
during the next login will not to be redirected to profile page.
|
321 |
"""
|
322 |
renew = forms.BooleanField(label='Renew token', required=False) |
323 |
|
324 |
class Meta: |
325 |
model = AstakosUser |
326 |
fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires') |
327 |
|
328 |
def __init__(self, *args, **kwargs): |
329 |
super(ProfileForm, self).__init__(*args, **kwargs) |
330 |
instance = getattr(self, 'instance', None) |
331 |
ro_fields = ('email', 'auth_token', 'auth_token_expires') |
332 |
if instance and instance.id: |
333 |
for field in ro_fields: |
334 |
self.fields[field].widget.attrs['readonly'] = True |
335 |
|
336 |
def save(self, commit=True): |
337 |
user = super(ProfileForm, self).save(commit=False) |
338 |
user.is_verified = True
|
339 |
if self.cleaned_data.get('renew'): |
340 |
user.renew_token() |
341 |
if commit:
|
342 |
user.save() |
343 |
return user
|
344 |
|
345 |
class FeedbackForm(forms.Form): |
346 |
"""
|
347 |
Form for writing feedback.
|
348 |
"""
|
349 |
feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
|
350 |
feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
|
351 |
required=False)
|
352 |
|
353 |
class SendInvitationForm(forms.Form): |
354 |
"""
|
355 |
Form for sending an invitations
|
356 |
"""
|
357 |
|
358 |
email = forms.EmailField(required = True, label = 'Email address') |
359 |
first_name = forms.EmailField(label = 'First name')
|
360 |
last_name = forms.EmailField(label = 'Last name')
|
361 |
|
362 |
class ExtendedPasswordResetForm(PasswordResetForm): |
363 |
"""
|
364 |
Extends PasswordResetForm by overriding save method:
|
365 |
passes a custom from_email in send_mail.
|
366 |
|
367 |
Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
|
368 |
accepts a from_email argument.
|
369 |
"""
|
370 |
def clean_email(self): |
371 |
email = super(ExtendedPasswordResetForm, self).clean_email() |
372 |
try:
|
373 |
user = AstakosUser.objects.get(email=email, is_active=True)
|
374 |
if not user.has_usable_password(): |
375 |
raise forms.ValidationError(_("This account has not a usable password.")) |
376 |
except AstakosUser.DoesNotExist, e:
|
377 |
raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?')) |
378 |
return email
|
379 |
|
380 |
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', |
381 |
use_https=False, token_generator=default_token_generator, request=None): |
382 |
"""
|
383 |
Generates a one-use only link for resetting password and sends to the user.
|
384 |
"""
|
385 |
for user in self.users_cache: |
386 |
url = reverse('django.contrib.auth.views.password_reset_confirm',
|
387 |
kwargs={'uidb36':int_to_base36(user.id),
|
388 |
'token':token_generator.make_token(user)})
|
389 |
url = request.build_absolute_uri(url) |
390 |
t = loader.get_template(email_template_name) |
391 |
c = { |
392 |
'email': user.email,
|
393 |
'url': url,
|
394 |
'site_name': SITENAME,
|
395 |
'user': user,
|
396 |
'baseurl': request.build_absolute_uri(),
|
397 |
'support': DEFAULT_CONTACT_EMAIL
|
398 |
} |
399 |
from_email = DEFAULT_FROM_EMAIL |
400 |
send_mail(_("Password reset on %s alpha2 testing") % SITENAME,
|
401 |
t.render(Context(c)), from_email, [user.email]) |
402 |
|
403 |
class SignApprovalTermsForm(forms.ModelForm): |
404 |
class Meta: |
405 |
model = AstakosUser |
406 |
fields = ("has_signed_terms",)
|
407 |
|
408 |
def __init__(self, *args, **kwargs): |
409 |
super(SignApprovalTermsForm, self).__init__(*args, **kwargs) |
410 |
|
411 |
def clean_has_signed_terms(self): |
412 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
413 |
if not has_signed_terms: |
414 |
raise forms.ValidationError(_('You have to agree with the terms')) |
415 |
return has_signed_terms
|
416 |
|
417 |
class InvitationForm(forms.ModelForm): |
418 |
username = forms.EmailField(label=_("Email"))
|
419 |
|
420 |
def __init__(self, *args, **kwargs): |
421 |
super(InvitationForm, self).__init__(*args, **kwargs) |
422 |
|
423 |
class Meta: |
424 |
model = Invitation |
425 |
fields = ('username', 'realname') |
426 |
|
427 |
def clean_username(self): |
428 |
username = self.cleaned_data['username'] |
429 |
try:
|
430 |
Invitation.objects.get(username = username) |
431 |
raise forms.ValidationError(_('There is already invitation for this email.')) |
432 |
except Invitation.DoesNotExist:
|
433 |
pass
|
434 |
return username
|