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