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