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