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