merge
[unfold.git] / portal / forms.py
1 # -*- coding: utf-8 -*-
2 #
3 # portal/forms.py: forms for the portal application
4 # This file is part of the Manifold project.
5 #
6 # Authors:
7 #   Jordan AugĂ© <jordan.auge@lip6.fr>
8 #   Mohammed-Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
9 # Copyright 2013, UPMC Sorbonne UniversitĂ©s / LIP6
10 #
11 # This program is free software; you can redistribute it and/or modify it under
12 # the terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 3, or (at your option) any later version.
14
15 # This program is distributed in the hope that it will be useful, but WITHOUT
16 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 # FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18 # details.
19
20 # You should have received a copy of the GNU General Public License along with
21 # this program; see the file COPYING.  If not, write to the Free Software
22 # Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23
24 # TODO: Remove these automated forms and use html templates and views like any other page !
25
26 from django import forms
27 #from crispy_forms.helper import FormHelper
28 #from crispy_forms.layout import Submit
29 from django.utils.translation import ugettext_lazy as _
30 from django.contrib.auth.tokens import default_token_generator
31 from django.contrib.auth import authenticate, get_user_model
32 from django.contrib.sites.models import get_current_site
33 from django.utils.http import int_to_base36
34 from django.template import loader
35
36 from django.contrib.auth.hashers import identify_hasher
37
38 from portal.models import PendingUser, PendingSlice
39
40 from myslice.settings import logger
41
42 # adapted from https://sourcegraph.com/github.com/fusionbox/django-authtools/symbols/python/authtools/forms
43
44 def is_password_unusable(pw):
45     # like Django's is_password_usable, but only checks for unusable
46     # passwords, not invalidly encoded passwords too.
47     try:
48         # 1.5
49         from django.contrib.auth.hashers import UNUSABLE_PASSWORD
50         return pw == UNUSABLE_PASSWORD
51     except ImportError:
52         # 1.6
53         from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX
54         return pw.startswith(UNUSABLE_PASSWORD_PREFIX)
55
56
57
58
59 # xxx painful, but... 
60 # bootstrap3 requires the <input> fields to be tagged class='form-control'
61 # my first idea was to add this in the view template of course, BUT
62 # I can't find a way to access the 'type=' value for a given field
63 # I've looked rather deeply out there but to no avail so far
64 # so as we have a demo coming up soon, and until we can come with a less intrusive way to handle this...
65
66 # initial version was
67 #class ContactForm(forms.Form):
68 #    first_name = forms.CharField()
69 #    last_name = forms.CharField()
70 #    affiliation = forms.CharField()
71 #    subject = forms.CharField(max_length=100)
72 #    message = forms.CharField(widget=forms.Textarea)
73 #    email = forms.EmailField()
74 #    cc_myself = forms.BooleanField(required=False)
75
76 class ContactForm(forms.Form):
77    # first_name = forms.RegexField(widget=forms.TextInput(attrs={'class':'form-control'}),
78    #                             regex=r'^[\w.@+-]+$',
79    #                              max_length=30,
80    #                              label=_("First name"),
81    #                              error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
82    # last_name = forms.RegexField(widget=forms.TextInput(attrs={'class':'form-control'}),
83    #                             regex=r'^[\w.@+-]+$',
84    #                              max_length=30,
85    #                              label=_("Last name"),
86    #                              error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
87    # authority = forms.RegexField(widget=forms.TextInput(attrs={'class':'form-control'}),
88    #                             regex=r'^[\w.@+-]+$',
89    #                              max_length=30,
90    #                              label=_("authority"),
91    #                              error_messages={'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
92     email = forms.EmailField(widget=forms.TextInput(attrs={'class':'form-control'}))
93     subject = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
94     description = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control'}))
95     #cc_myself = forms.BooleanField(required=False,widget=forms.CheckboxInput(attrs={'class':'form-control'}))
96
97 class PassResetForm(forms.Form):
98     email = forms.EmailField(widget=forms.TextInput(attrs={'class':'form-control'}))
99
100 #class SliceRequestForm(forms.Form):
101 #    slice_name = forms.CharField()
102 #    authority_hrn = forms.ChoiceField(choices=[(1, 'un')])
103 #    number_of_nodes  = forms.DecimalField()
104 #    type_of_nodes = forms.CharField()
105 #    purpose = forms.CharField(widget=forms.Textarea)
106 #    email = forms.EmailField()
107 #    cc_myself = forms.BooleanField(required=False)
108 #
109 #    slice_name = forms.CharField(
110 #        widget=forms.TextInput(attrs={'class':'form-control'}), 
111 #        help_text="The name for the slice you wish to create")
112 #    authority_hrn = forms.ChoiceField(
113 #        widget    = forms.Select(attrs={'class':'form-control'}),
114 #        choices   = [],
115 #        help_text = "An authority responsible for vetting your slice")
116 #    number_of_nodes = forms.DecimalField(
117 #        widget    = forms.TextInput(attrs={'class':'form-control'}),
118 #        help_text = "The number of nodes you expect to request (informative)")
119 #    type_of_nodes = forms.CharField(
120 #        widget    = forms.TextInput(attrs={'class':'form-control'}),
121 #        help_text = "The type of nodes you expect to request (informative)")
122 #    purpose = forms.CharField(
123 #        widget    = forms.Textarea(attrs={'class':'form-control'}),
124 #        help_text = "The purpose of your experiment (informative)")
125 #    email = forms.EmailField(
126 #        widget    = forms.TextInput(attrs={'class':'form-control'}),
127 #        help_text = "Your email address")
128 #    cc_myself = forms.BooleanField(
129 #        widget    = forms.CheckboxInput(attrs={'class':'form-control'}),
130 #        required  = False,
131 #        help_text = "If you'd like to be cc'ed on the request email")
132 #
133 #    def __init__(self, *args, **kwargs):
134 #        initial =  kwargs.get('initial', {})
135 #        authority_hrn = initial.get('authority_hrn', None)
136 #
137 #        # set just the initial value
138 #        # in the real form needs something like this {'authority_hrn':'a'}
139 #        # but in this case you want {'authority_hrn':('a', 'letter_a')}
140 #        if authority_hrn:
141 #            kwargs['initial']['authority_hrn'] = authority_hrn[0]
142 #
143 #        # create the form
144 #        super(SliceRequestForm, self).__init__(*args, **kwargs)
145 #
146 #        # self.fields only exist after, so a double validation is needed
147 #        if authority_hrn:# and authority_hrn[0] not in (c[0] for c in authority_hrn):
148 #            # XXX This does not work, the choicefield is not updated...
149 #            #self.fields['authority_hrn'].choices.extend(authority_hrn)
150 #            self.fields['authority_hrn'] = forms.ChoiceField(
151 #                widget    = forms.Select(attrs={'class':'form-control'}),
152 #                choices   = authority_hrn,
153 #                help_text = "An authority responsible for vetting your slice")
154
155
156 class PasswordResetForm(forms.Form):
157     error_messages = {
158         'unknown': _("That email address doesn't have an associated "
159                      "user account. Are you sure you've registered?"),
160         'unusable': _("The user account associated with this email "
161                       "address cannot reset the password."),
162     }
163     email = forms.EmailField(label=_("Email"), max_length=254)
164
165     def clean_email(self):
166         """
167         Validates that an active user exists with the given email address.
168         """
169         UserModel = get_user_model()
170         email = self.cleaned_data["email"]
171         self.users_cache = UserModel._default_manager.filter(email__iexact=email)
172         if not len(self.users_cache):
173             raise forms.ValidationError(self.error_messages['unknown'])
174         if not any(user.is_active for user in self.users_cache):
175             # none of the filtered users are active
176             raise forms.ValidationError(self.error_messages['unknown'])
177         if any(is_password_unusable(user.password) for user in self.users_cache):
178             raise forms.ValidationError(self.error_messages['unusable'])
179         return email
180
181     def save(self, domain_override=None,
182              subject_template_name='registration/password_reset_subject.txt',
183              email_template_name='registration/password_reset_email.html',
184              use_https=False, token_generator=default_token_generator,
185              from_email=None, request=None):
186         """
187         Generates a one-use only link for resetting password and sends to the
188         user.
189         """
190         from django.core.mail import send_mail,EmailMultiAlternatives
191         try:        
192             for user in self.users_cache:
193                 if not domain_override:
194                     current_site = get_current_site(request)
195                     site_name = current_site.name
196                     domain = current_site.domain
197                 else:
198                     site_name = domain = domain_override
199                 c = {
200                     'email': user.email,
201                     'domain': domain,
202                     'site_name': site_name,
203                     'uid': int_to_base36(user.pk),
204                     'user': user,
205                     'token': token_generator.make_token(user),
206                     'protocol': use_https and 'https' or 'http',
207                 }
208                 subject = loader.render_to_string(subject_template_name, c)
209                 # Email subject *must not* contain newlines
210                 subject = ''.join(subject.splitlines())
211                 email = loader.render_to_string(email_template_name, c)
212                 send_mail(subject, email, from_email, [user.email])
213         except Exception as e:
214             logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
215
216
217 class SetPasswordForm(forms.Form):
218     """
219     A form that lets a user change set his/her password without entering the
220     old password
221     """
222     error_messages = {
223         'password_mismatch': _("The two password fields didn't match."),
224     }
225     new_password1 = forms.CharField(label=_("New password"),
226                                     widget=forms.PasswordInput)
227     new_password2 = forms.CharField(label=_("New password confirmation"),
228                                     widget=forms.PasswordInput)
229
230     def __init__(self, user, *args, **kwargs):
231         self.user = user
232         super(SetPasswordForm, self).__init__(*args, **kwargs)
233
234     def clean_new_password2(self):
235         password1 = self.cleaned_data.get('new_password1')
236         password2 = self.cleaned_data.get('new_password2')
237         if password1 and password2:
238             if password1 != password2:
239                 raise forms.ValidationError(
240                     self.error_messages['password_mismatch'])
241         return password2
242
243     def save(self, commit=True):
244         self.user.set_password(self.cleaned_data['new_password1'])
245         if commit:
246             self.user.save()
247         return self.user
248