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