root / snf-astakos-app / astakos / im / forms.py @ 111f3da6
History | View | Annotate | Download (18.1 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 |
from django.utils.encoding import smart_str |
48 |
|
49 |
from astakos.im.models import AstakosUser, Invitation, get_latest_terms, EmailChange |
50 |
from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, \ |
51 |
BASEURL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL, \ |
52 |
RECAPTCHA_ENABLED, LOGGING_LEVEL |
53 |
from astakos.im.widgets import DummyWidget, RecaptchaWidget |
54 |
from astakos.im.functions import send_change_email |
55 |
|
56 |
# since Django 1.4 use django.core.urlresolvers.reverse_lazy instead
|
57 |
from astakos.im.util import reverse_lazy, reserved_email, get_query |
58 |
|
59 |
import logging |
60 |
import hashlib |
61 |
import recaptcha.client.captcha as captcha |
62 |
from random import random |
63 |
|
64 |
logger = logging.getLogger(__name__) |
65 |
|
66 |
class LocalUserCreationForm(UserCreationForm): |
67 |
"""
|
68 |
Extends the built in UserCreationForm in several ways:
|
69 |
|
70 |
* Adds email, first_name, last_name, recaptcha_challenge_field, recaptcha_response_field field.
|
71 |
* The username field isn't visible and it is assigned a generated id.
|
72 |
* User created is not active.
|
73 |
"""
|
74 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
75 |
recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
|
76 |
|
77 |
class Meta: |
78 |
model = AstakosUser |
79 |
fields = ("email", "first_name", "last_name", "has_signed_terms", "has_signed_terms") |
80 |
|
81 |
def __init__(self, *args, **kwargs): |
82 |
"""
|
83 |
Changes the order of fields, and removes the username field.
|
84 |
"""
|
85 |
request = kwargs.get('request', None) |
86 |
if request:
|
87 |
kwargs.pop('request')
|
88 |
self.ip = request.META.get('REMOTE_ADDR', |
89 |
request.META.get('HTTP_X_REAL_IP', None)) |
90 |
|
91 |
super(LocalUserCreationForm, self).__init__(*args, **kwargs) |
92 |
self.fields.keyOrder = ['email', 'first_name', 'last_name', |
93 |
'password1', 'password2'] |
94 |
if get_latest_terms():
|
95 |
self.fields.keyOrder.append('has_signed_terms') |
96 |
if RECAPTCHA_ENABLED:
|
97 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
98 |
'recaptcha_response_field',])
|
99 |
|
100 |
if 'has_signed_terms' in self.fields: |
101 |
# Overriding field label since we need to apply a link
|
102 |
# to the terms within the label
|
103 |
terms_link_html = '<a href="%s" target="_blank">%s</a>' \
|
104 |
% (reverse('latest_terms'), _("the terms")) |
105 |
self.fields['has_signed_terms'].label = \ |
106 |
mark_safe("I agree with %s" % terms_link_html)
|
107 |
|
108 |
def clean_email(self): |
109 |
email = self.cleaned_data['email'] |
110 |
if not email: |
111 |
raise forms.ValidationError(_("This field is required")) |
112 |
if reserved_email(email):
|
113 |
raise forms.ValidationError(_("This email is already used")) |
114 |
return email
|
115 |
|
116 |
def clean_has_signed_terms(self): |
117 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
118 |
if not has_signed_terms: |
119 |
raise forms.ValidationError(_('You have to agree with the terms')) |
120 |
return has_signed_terms
|
121 |
|
122 |
def clean_recaptcha_response_field(self): |
123 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
124 |
self.validate_captcha()
|
125 |
return self.cleaned_data['recaptcha_response_field'] |
126 |
|
127 |
def clean_recaptcha_challenge_field(self): |
128 |
if 'recaptcha_response_field' in self.cleaned_data: |
129 |
self.validate_captcha()
|
130 |
return self.cleaned_data['recaptcha_challenge_field'] |
131 |
|
132 |
def validate_captcha(self): |
133 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
134 |
rrf = self.cleaned_data['recaptcha_response_field'] |
135 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
136 |
if not check.is_valid: |
137 |
raise forms.ValidationError(_('You have not entered the correct words')) |
138 |
|
139 |
def save(self, commit=True): |
140 |
"""
|
141 |
Saves the email, first_name and last_name properties, after the normal
|
142 |
save behavior is complete.
|
143 |
"""
|
144 |
user = super(LocalUserCreationForm, self).save(commit=False) |
145 |
user.renew_token() |
146 |
if commit:
|
147 |
user.save() |
148 |
logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, [])
|
149 |
return user
|
150 |
|
151 |
class InvitedLocalUserCreationForm(LocalUserCreationForm): |
152 |
"""
|
153 |
Extends the LocalUserCreationForm: email is readonly.
|
154 |
"""
|
155 |
class Meta: |
156 |
model = AstakosUser |
157 |
fields = ("email", "first_name", "last_name", "has_signed_terms") |
158 |
|
159 |
def __init__(self, *args, **kwargs): |
160 |
"""
|
161 |
Changes the order of fields, and removes the username field.
|
162 |
"""
|
163 |
super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs) |
164 |
|
165 |
#set readonly form fields
|
166 |
ro = ('email', 'username',) |
167 |
for f in ro: |
168 |
self.fields[f].widget.attrs['readonly'] = True |
169 |
|
170 |
|
171 |
def save(self, commit=True): |
172 |
user = super(InvitedLocalUserCreationForm, self).save(commit=False) |
173 |
level = user.invitation.inviter.level + 1
|
174 |
user.level = level |
175 |
user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
|
176 |
user.email_verified = True
|
177 |
if commit:
|
178 |
user.save() |
179 |
return user
|
180 |
|
181 |
class ThirdPartyUserCreationForm(forms.ModelForm): |
182 |
class Meta: |
183 |
model = AstakosUser |
184 |
fields = ("email", "first_name", "last_name", "third_party_identifier", "has_signed_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 |
return email
|
215 |
|
216 |
def clean_has_signed_terms(self): |
217 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
218 |
if not has_signed_terms: |
219 |
raise forms.ValidationError(_('You have to agree with the terms')) |
220 |
return has_signed_terms
|
221 |
|
222 |
def save(self, commit=True): |
223 |
user = super(ThirdPartyUserCreationForm, self).save(commit=False) |
224 |
user.set_unusable_password() |
225 |
user.renew_token() |
226 |
user.provider = get_query(self.request).get('provider') |
227 |
if commit:
|
228 |
user.save() |
229 |
logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, [])
|
230 |
return user
|
231 |
|
232 |
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm): |
233 |
"""
|
234 |
Extends the ThirdPartyUserCreationForm: email is readonly.
|
235 |
"""
|
236 |
def __init__(self, *args, **kwargs): |
237 |
"""
|
238 |
Changes the order of fields, and removes the username field.
|
239 |
"""
|
240 |
super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs) |
241 |
|
242 |
#set readonly form fields
|
243 |
ro = ('email',)
|
244 |
for f in ro: |
245 |
self.fields[f].widget.attrs['readonly'] = True |
246 |
|
247 |
def save(self, commit=True): |
248 |
user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False) |
249 |
level = user.invitation.inviter.level + 1
|
250 |
user.level = level |
251 |
user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
|
252 |
user.email_verified = True
|
253 |
if commit:
|
254 |
user.save() |
255 |
return user
|
256 |
|
257 |
class ShibbolethUserCreationForm(ThirdPartyUserCreationForm): |
258 |
def clean_email(self): |
259 |
email = self.cleaned_data['email'] |
260 |
for user in AstakosUser.objects.filter(email = email): |
261 |
if user.provider == 'shibboleth': |
262 |
raise forms.ValidationError(_("This email is already associated with another shibboleth account.")) |
263 |
elif not user.is_active: |
264 |
raise forms.ValidationError(_("This email is already associated with an inactive account. \ |
265 |
You need to wait to be activated before being able to switch to a shibboleth account."))
|
266 |
super(ShibbolethUserCreationForm, self).clean_email() |
267 |
return email
|
268 |
|
269 |
class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, InvitedThirdPartyUserCreationForm): |
270 |
pass
|
271 |
|
272 |
class LoginForm(AuthenticationForm): |
273 |
username = forms.EmailField(label=_("Email"))
|
274 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
275 |
recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
|
276 |
|
277 |
def __init__(self, *args, **kwargs): |
278 |
was_limited = kwargs.get('was_limited', False) |
279 |
request = kwargs.get('request', None) |
280 |
if request:
|
281 |
self.ip = request.META.get('REMOTE_ADDR', |
282 |
request.META.get('HTTP_X_REAL_IP', None)) |
283 |
|
284 |
t = ('request', 'was_limited') |
285 |
for elem in t: |
286 |
if elem in kwargs.keys(): |
287 |
kwargs.pop(elem) |
288 |
super(LoginForm, self).__init__(*args, **kwargs) |
289 |
|
290 |
self.fields.keyOrder = ['username', 'password'] |
291 |
if was_limited and RECAPTCHA_ENABLED: |
292 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
293 |
'recaptcha_response_field',])
|
294 |
|
295 |
def clean_recaptcha_response_field(self): |
296 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
297 |
self.validate_captcha()
|
298 |
return self.cleaned_data['recaptcha_response_field'] |
299 |
|
300 |
def clean_recaptcha_challenge_field(self): |
301 |
if 'recaptcha_response_field' in self.cleaned_data: |
302 |
self.validate_captcha()
|
303 |
return self.cleaned_data['recaptcha_challenge_field'] |
304 |
|
305 |
def validate_captcha(self): |
306 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
307 |
rrf = self.cleaned_data['recaptcha_response_field'] |
308 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
309 |
if not check.is_valid: |
310 |
raise forms.ValidationError(_('You have not entered the correct words')) |
311 |
|
312 |
class ProfileForm(forms.ModelForm): |
313 |
"""
|
314 |
Subclass of ``ModelForm`` for permiting user to edit his/her profile.
|
315 |
Most of the fields are readonly since the user is not allowed to change them.
|
316 |
|
317 |
The class defines a save method which sets ``is_verified`` to True so as the user
|
318 |
during the next login will not to be redirected to profile page.
|
319 |
"""
|
320 |
renew = forms.BooleanField(label='Renew token', required=False) |
321 |
|
322 |
class Meta: |
323 |
model = AstakosUser |
324 |
fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires') |
325 |
|
326 |
def __init__(self, *args, **kwargs): |
327 |
super(ProfileForm, self).__init__(*args, **kwargs) |
328 |
instance = getattr(self, 'instance', None) |
329 |
ro_fields = ('email', 'auth_token', 'auth_token_expires') |
330 |
if instance and instance.id: |
331 |
for field in ro_fields: |
332 |
self.fields[field].widget.attrs['readonly'] = True |
333 |
|
334 |
def save(self, commit=True): |
335 |
user = super(ProfileForm, self).save(commit=False) |
336 |
user.is_verified = True
|
337 |
if self.cleaned_data.get('renew'): |
338 |
user.renew_token() |
339 |
if commit:
|
340 |
user.save() |
341 |
return user
|
342 |
|
343 |
class FeedbackForm(forms.Form): |
344 |
"""
|
345 |
Form for writing feedback.
|
346 |
"""
|
347 |
feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
|
348 |
feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
|
349 |
required=False)
|
350 |
|
351 |
class SendInvitationForm(forms.Form): |
352 |
"""
|
353 |
Form for sending an invitations
|
354 |
"""
|
355 |
|
356 |
email = forms.EmailField(required = True, label = 'Email address') |
357 |
first_name = forms.EmailField(label = 'First name')
|
358 |
last_name = forms.EmailField(label = 'Last name')
|
359 |
|
360 |
class ExtendedPasswordResetForm(PasswordResetForm): |
361 |
"""
|
362 |
Extends PasswordResetForm by overriding save method:
|
363 |
passes a custom from_email in send_mail.
|
364 |
|
365 |
Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
|
366 |
accepts a from_email argument.
|
367 |
"""
|
368 |
def clean_email(self): |
369 |
email = super(ExtendedPasswordResetForm, self).clean_email() |
370 |
try:
|
371 |
user = AstakosUser.objects.get(email=email, is_active=True)
|
372 |
if not user.has_usable_password(): |
373 |
raise forms.ValidationError(_("This account has not a usable password.")) |
374 |
except AstakosUser.DoesNotExist, e:
|
375 |
raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?')) |
376 |
return email
|
377 |
|
378 |
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', |
379 |
use_https=False, token_generator=default_token_generator, request=None): |
380 |
"""
|
381 |
Generates a one-use only link for resetting password and sends to the user.
|
382 |
"""
|
383 |
for user in self.users_cache: |
384 |
url = reverse('django.contrib.auth.views.password_reset_confirm',
|
385 |
kwargs={'uidb36':int_to_base36(user.id),
|
386 |
'token':token_generator.make_token(user)})
|
387 |
url = urljoin(BASEURL, url) |
388 |
t = loader.get_template(email_template_name) |
389 |
c = { |
390 |
'email': user.email,
|
391 |
'url': url,
|
392 |
'site_name': SITENAME,
|
393 |
'user': user,
|
394 |
'baseurl': BASEURL,
|
395 |
'support': DEFAULT_CONTACT_EMAIL
|
396 |
} |
397 |
from_email = DEFAULT_FROM_EMAIL |
398 |
send_mail(_("Password reset on %s alpha2 testing") % SITENAME,
|
399 |
t.render(Context(c)), from_email, [user.email]) |
400 |
|
401 |
class EmailChangeForm(forms.ModelForm): |
402 |
class Meta: |
403 |
model = EmailChange |
404 |
fields = ('new_email_address',)
|
405 |
|
406 |
def clean_new_email_address(self): |
407 |
addr = self.cleaned_data['new_email_address'] |
408 |
if AstakosUser.objects.filter(email__iexact=addr):
|
409 |
raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.')) |
410 |
return addr
|
411 |
|
412 |
def save(self, email_template_name, request, commit=True): |
413 |
ec = super(EmailChangeForm, self).save(commit=False) |
414 |
ec.user = request.user |
415 |
activation_key = hashlib.sha1(str(random()) + smart_str(ec.new_email_address))
|
416 |
ec.activation_key=activation_key.hexdigest() |
417 |
if commit:
|
418 |
ec.save() |
419 |
send_change_email(ec, request, email_template_name=email_template_name) |
420 |
|
421 |
class SignApprovalTermsForm(forms.ModelForm): |
422 |
class Meta: |
423 |
model = AstakosUser |
424 |
fields = ("has_signed_terms",)
|
425 |
|
426 |
def __init__(self, *args, **kwargs): |
427 |
super(SignApprovalTermsForm, self).__init__(*args, **kwargs) |
428 |
|
429 |
def clean_has_signed_terms(self): |
430 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
431 |
if not has_signed_terms: |
432 |
raise forms.ValidationError(_('You have to agree with the terms')) |
433 |
return has_signed_terms
|
434 |
|
435 |
class InvitationForm(forms.ModelForm): |
436 |
username = forms.EmailField(label=_("Email"))
|
437 |
|
438 |
def __init__(self, *args, **kwargs): |
439 |
super(InvitationForm, self).__init__(*args, **kwargs) |
440 |
|
441 |
class Meta: |
442 |
model = Invitation |
443 |
fields = ('username', 'realname') |
444 |
|
445 |
def clean_username(self): |
446 |
username = self.cleaned_data['username'] |
447 |
try:
|
448 |
Invitation.objects.get(username = username) |
449 |
raise forms.ValidationError(_('There is already invitation for this email.')) |
450 |
except Invitation.DoesNotExist:
|
451 |
pass
|
452 |
return username
|