root / snf-astakos-app / astakos / im / forms.py @ a70dacde
History | View | Annotate | Download (12.5 kB)
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, PasswordResetForm |
39 |
from django.core.mail import send_mail |
40 |
from django.contrib.auth.tokens import default_token_generator |
41 |
from django.template import Context, loader |
42 |
from django.utils.http import int_to_base36 |
43 |
from django.core.urlresolvers import reverse |
44 |
from django.utils.functional import lazy |
45 |
from django.utils.safestring import mark_safe |
46 |
|
47 |
from astakos.im.models import AstakosUser |
48 |
from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, BASEURL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL, RECAPTCHA_ENABLED |
49 |
from astakos.im.widgets import DummyWidget, RecaptchaWidget, ApprovalTermsWidget |
50 |
|
51 |
# since Django 1.4 use django.core.urlresolvers.reverse_lazy instead
|
52 |
from astakos.im.util import reverse_lazy, get_latest_terms |
53 |
|
54 |
import logging |
55 |
import recaptcha.client.captcha as captcha |
56 |
|
57 |
logger = logging.getLogger(__name__) |
58 |
|
59 |
class LocalUserCreationForm(UserCreationForm): |
60 |
"""
|
61 |
Extends the built in UserCreationForm in several ways:
|
62 |
|
63 |
* Adds email, first_name, last_name, recaptcha_challenge_field, recaptcha_response_field field.
|
64 |
* The username field isn't visible and it is assigned a generated id.
|
65 |
* User created is not active.
|
66 |
"""
|
67 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
68 |
recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
|
69 |
|
70 |
class Meta: |
71 |
model = AstakosUser |
72 |
fields = ("email", "first_name", "last_name", "has_signed_terms") |
73 |
widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))} |
74 |
|
75 |
def __init__(self, *args, **kwargs): |
76 |
"""
|
77 |
Changes the order of fields, and removes the username field.
|
78 |
"""
|
79 |
if 'ip' in kwargs: |
80 |
self.ip = kwargs['ip'] |
81 |
kwargs.pop('ip')
|
82 |
super(LocalUserCreationForm, self).__init__(*args, **kwargs) |
83 |
self.fields.keyOrder = ['email', 'first_name', 'last_name', |
84 |
'password1', 'password2'] |
85 |
if get_latest_terms():
|
86 |
self.fields.keyOrder.append('has_signed_terms') |
87 |
if RECAPTCHA_ENABLED:
|
88 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
89 |
'recaptcha_response_field',])
|
90 |
|
91 |
if 'has_signed_terms' in self.fields: |
92 |
# Overriding field label since we need to apply a link
|
93 |
# to the terms within the label
|
94 |
terms_link_html = '<a href="%s" target="_blank">%s</a>' \
|
95 |
% (reverse('latest_terms'), _("the terms")) |
96 |
self.fields['has_signed_terms'].label = \ |
97 |
mark_safe("I agree with %s" % terms_link_html)
|
98 |
|
99 |
def clean_email(self): |
100 |
email = self.cleaned_data['email'] |
101 |
if not email: |
102 |
raise forms.ValidationError(_("This field is required")) |
103 |
try:
|
104 |
AstakosUser.objects.get(email = email) |
105 |
raise forms.ValidationError(_("This email is already used")) |
106 |
except AstakosUser.DoesNotExist:
|
107 |
return email
|
108 |
|
109 |
def clean_has_signed_terms(self): |
110 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
111 |
if not has_signed_terms: |
112 |
raise forms.ValidationError(_('You have to agree with the terms')) |
113 |
return has_signed_terms
|
114 |
|
115 |
def clean_recaptcha_response_field(self): |
116 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
117 |
self.validate_captcha()
|
118 |
return self.cleaned_data['recaptcha_response_field'] |
119 |
|
120 |
def clean_recaptcha_challenge_field(self): |
121 |
if 'recaptcha_response_field' in self.cleaned_data: |
122 |
self.validate_captcha()
|
123 |
return self.cleaned_data['recaptcha_challenge_field'] |
124 |
|
125 |
def validate_captcha(self): |
126 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
127 |
rrf = self.cleaned_data['recaptcha_response_field'] |
128 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
129 |
if not check.is_valid: |
130 |
raise forms.ValidationError(_('You have not entered the correct words')) |
131 |
|
132 |
def save(self, commit=True): |
133 |
"""
|
134 |
Saves the email, first_name and last_name properties, after the normal
|
135 |
save behavior is complete.
|
136 |
"""
|
137 |
user = super(LocalUserCreationForm, self).save(commit=False) |
138 |
user.renew_token() |
139 |
user.date_signed_terms = datetime.now() |
140 |
if commit:
|
141 |
user.save() |
142 |
logger.info('Created user %s', user)
|
143 |
return user
|
144 |
|
145 |
class InvitedLocalUserCreationForm(LocalUserCreationForm): |
146 |
"""
|
147 |
Extends the LocalUserCreationForm: adds an inviter readonly field.
|
148 |
"""
|
149 |
|
150 |
inviter = forms.CharField(widget=forms.TextInput(), label=_('Inviter Real Name'))
|
151 |
|
152 |
class Meta: |
153 |
model = AstakosUser |
154 |
fields = ("email", "first_name", "last_name", "has_signed_terms") |
155 |
widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))} |
156 |
|
157 |
def __init__(self, *args, **kwargs): |
158 |
"""
|
159 |
Changes the order of fields, and removes the username field.
|
160 |
"""
|
161 |
super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs) |
162 |
|
163 |
#set readonly form fields
|
164 |
self.fields['inviter'].widget.attrs['readonly'] = True |
165 |
self.fields['email'].widget.attrs['readonly'] = True |
166 |
self.fields['username'].widget.attrs['readonly'] = True |
167 |
|
168 |
def save(self, commit=True): |
169 |
user = super(InvitedLocalUserCreationForm, self).save(commit=False) |
170 |
level = user.invitation.inviter.level + 1
|
171 |
user.level = level |
172 |
user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
|
173 |
user.email_verified = True
|
174 |
if commit:
|
175 |
user.save() |
176 |
return user
|
177 |
|
178 |
class LoginForm(AuthenticationForm): |
179 |
username = forms.EmailField(label=_("Email"))
|
180 |
|
181 |
class ProfileForm(forms.ModelForm): |
182 |
"""
|
183 |
Subclass of ``ModelForm`` for permiting user to edit his/her profile.
|
184 |
Most of the fields are readonly since the user is not allowed to change them.
|
185 |
|
186 |
The class defines a save method which sets ``is_verified`` to True so as the user
|
187 |
during the next login will not to be redirected to profile page.
|
188 |
"""
|
189 |
renew = forms.BooleanField(label='Renew token', required=False) |
190 |
|
191 |
class Meta: |
192 |
model = AstakosUser |
193 |
fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires') |
194 |
|
195 |
def __init__(self, *args, **kwargs): |
196 |
super(ProfileForm, self).__init__(*args, **kwargs) |
197 |
instance = getattr(self, 'instance', None) |
198 |
ro_fields = ('auth_token', 'auth_token_expires', 'email') |
199 |
if instance and instance.id: |
200 |
for field in ro_fields: |
201 |
self.fields[field].widget.attrs['readonly'] = True |
202 |
|
203 |
def save(self, commit=True): |
204 |
user = super(ProfileForm, self).save(commit=False) |
205 |
user.is_verified = True
|
206 |
if self.cleaned_data.get('renew'): |
207 |
user.renew_token() |
208 |
if commit:
|
209 |
user.save() |
210 |
return user
|
211 |
|
212 |
class ThirdPartyUserCreationForm(ProfileForm): |
213 |
class Meta: |
214 |
model = AstakosUser |
215 |
fields = ('email', 'last_name', 'first_name', 'affiliation', 'provider', 'third_party_identifier') |
216 |
|
217 |
def __init__(self, *args, **kwargs): |
218 |
if 'ip' in kwargs: |
219 |
self.ip = kwargs['ip'] |
220 |
kwargs.pop('ip')
|
221 |
super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs) |
222 |
self.fields.keyOrder = ['email'] |
223 |
|
224 |
def clean_email(self): |
225 |
email = self.cleaned_data['email'] |
226 |
if not email: |
227 |
raise forms.ValidationError(_("This field is required")) |
228 |
try:
|
229 |
user = AstakosUser.objects.get(email = email) |
230 |
raise forms.ValidationError(_("This email is already used")) |
231 |
except AstakosUser.DoesNotExist:
|
232 |
return email
|
233 |
|
234 |
def save(self, commit=True): |
235 |
user = super(ThirdPartyUserCreationForm, self).save(commit=False) |
236 |
user.verified = False
|
237 |
user.renew_token() |
238 |
if commit:
|
239 |
user.save() |
240 |
logger.info('Created user %s', user)
|
241 |
return user
|
242 |
|
243 |
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm): |
244 |
def __init__(self, *args, **kwargs): |
245 |
super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs) |
246 |
#set readonly form fields
|
247 |
self.fields['email'].widget.attrs['readonly'] = True |
248 |
|
249 |
class FeedbackForm(forms.Form): |
250 |
"""
|
251 |
Form for writing feedback.
|
252 |
"""
|
253 |
feedback_msg = forms.CharField(widget=forms.Textarea(), |
254 |
label=u'Message', required=False) |
255 |
feedback_data = forms.CharField(widget=forms.HiddenInput(), |
256 |
label='', required=False) |
257 |
|
258 |
class SendInvitationForm(forms.Form): |
259 |
"""
|
260 |
Form for sending an invitations
|
261 |
"""
|
262 |
|
263 |
email = forms.EmailField(required = True, label = 'Email address') |
264 |
first_name = forms.EmailField(label = 'First name')
|
265 |
last_name = forms.EmailField(label = 'Last name')
|
266 |
|
267 |
class ExtendedPasswordResetForm(PasswordResetForm): |
268 |
"""
|
269 |
Extends PasswordResetForm by overriding save method:
|
270 |
passes a custom from_email in send_mail.
|
271 |
|
272 |
Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
|
273 |
accepts a from_email argument.
|
274 |
"""
|
275 |
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', |
276 |
use_https=False, token_generator=default_token_generator, request=None): |
277 |
"""
|
278 |
Generates a one-use only link for resetting password and sends to the user.
|
279 |
"""
|
280 |
for user in self.users_cache: |
281 |
url = urljoin(BASEURL, |
282 |
'/im/local/reset/confirm/%s-%s' %(int_to_base36(user.id),
|
283 |
token_generator.make_token(user))) |
284 |
t = loader.get_template(email_template_name) |
285 |
c = { |
286 |
'email': user.email,
|
287 |
'url': url,
|
288 |
'site_name': SITENAME,
|
289 |
'user': user,
|
290 |
'baseurl': BASEURL,
|
291 |
'support': DEFAULT_CONTACT_EMAIL
|
292 |
} |
293 |
from_email = DEFAULT_FROM_EMAIL |
294 |
send_mail(_("Password reset on %s alpha2 testing") % SITENAME,
|
295 |
t.render(Context(c)), from_email, [user.email]) |
296 |
|
297 |
class SignApprovalTermsForm(forms.ModelForm): |
298 |
class Meta: |
299 |
model = AstakosUser |
300 |
fields = ("has_signed_terms",)
|
301 |
|
302 |
def __init__(self, *args, **kwargs): |
303 |
super(SignApprovalTermsForm, self).__init__(*args, **kwargs) |
304 |
|
305 |
def clean_has_signed_terms(self): |
306 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
307 |
if not has_signed_terms: |
308 |
raise forms.ValidationError(_('You have to agree with the terms')) |
309 |
return has_signed_terms
|
310 |
|
311 |
def save(self, commit=True): |
312 |
"""
|
313 |
Saves the , after the normal
|
314 |
save behavior is complete.
|
315 |
"""
|
316 |
user = super(SignApprovalTermsForm, self).save(commit=False) |
317 |
user.date_signed_terms = datetime.now() |
318 |
if commit:
|
319 |
user.save() |
320 |
return user
|