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