root / snf-astakos-app / astakos / im / forms.py @ 062c970c
History | View | Annotate | Download (17.1 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 |
from django.contrib import messages |
47 |
|
48 |
from astakos.im.models import AstakosUser, Invitation, get_latest_terms |
49 |
from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL, RECAPTCHA_ENABLED |
50 |
from astakos.im.widgets import DummyWidget, RecaptchaWidget, ApprovalTermsWidget |
51 |
|
52 |
# since Django 1.4 use django.core.urlresolvers.reverse_lazy instead
|
53 |
from astakos.im.util import reverse_lazy, reserved_email, get_query |
54 |
|
55 |
import logging |
56 |
import recaptcha.client.captcha as captcha |
57 |
|
58 |
logger = logging.getLogger(__name__) |
59 |
|
60 |
class LocalUserCreationForm(UserCreationForm): |
61 |
"""
|
62 |
Extends the built in UserCreationForm in several ways:
|
63 |
|
64 |
* Adds email, first_name, last_name, recaptcha_challenge_field, recaptcha_response_field field.
|
65 |
* The username field isn't visible and it is assigned a generated id.
|
66 |
* User created is not active.
|
67 |
"""
|
68 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
69 |
recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
|
70 |
|
71 |
class Meta: |
72 |
model = AstakosUser |
73 |
fields = ("email", "first_name", "last_name", "has_signed_terms") |
74 |
widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))} |
75 |
|
76 |
def __init__(self, *args, **kwargs): |
77 |
"""
|
78 |
Changes the order of fields, and removes the username field.
|
79 |
"""
|
80 |
request = kwargs.get('request', None) |
81 |
if request:
|
82 |
kwargs.pop('request')
|
83 |
self.ip = request.META.get('REMOTE_ADDR', |
84 |
request.META.get('HTTP_X_REAL_IP', None)) |
85 |
|
86 |
super(LocalUserCreationForm, self).__init__(*args, **kwargs) |
87 |
self.fields.keyOrder = ['email', 'first_name', 'last_name', |
88 |
'password1', 'password2'] |
89 |
if get_latest_terms():
|
90 |
self.fields.keyOrder.append('has_signed_terms') |
91 |
if RECAPTCHA_ENABLED:
|
92 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
93 |
'recaptcha_response_field',])
|
94 |
|
95 |
if 'has_signed_terms' in self.fields: |
96 |
# Overriding field label since we need to apply a link
|
97 |
# to the terms within the label
|
98 |
terms_link_html = '<a href="%s" target="_blank">%s</a>' \
|
99 |
% (reverse('latest_terms'), _("the terms")) |
100 |
self.fields['has_signed_terms'].label = \ |
101 |
mark_safe("I agree with %s" % terms_link_html)
|
102 |
|
103 |
def clean_email(self): |
104 |
email = self.cleaned_data['email'] |
105 |
if not email: |
106 |
raise forms.ValidationError(_("This field is required")) |
107 |
if reserved_email(email):
|
108 |
raise forms.ValidationError(_("This email is already used")) |
109 |
return email
|
110 |
|
111 |
def clean_has_signed_terms(self): |
112 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
113 |
if not has_signed_terms: |
114 |
raise forms.ValidationError(_('You have to agree with the terms')) |
115 |
return has_signed_terms
|
116 |
|
117 |
def clean_recaptcha_response_field(self): |
118 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
119 |
self.validate_captcha()
|
120 |
return self.cleaned_data['recaptcha_response_field'] |
121 |
|
122 |
def clean_recaptcha_challenge_field(self): |
123 |
if 'recaptcha_response_field' in self.cleaned_data: |
124 |
self.validate_captcha()
|
125 |
return self.cleaned_data['recaptcha_challenge_field'] |
126 |
|
127 |
def validate_captcha(self): |
128 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
129 |
rrf = self.cleaned_data['recaptcha_response_field'] |
130 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
131 |
if not check.is_valid: |
132 |
raise forms.ValidationError(_('You have not entered the correct words')) |
133 |
|
134 |
def save(self, commit=True): |
135 |
"""
|
136 |
Saves the email, first_name and last_name properties, after the normal
|
137 |
save behavior is complete.
|
138 |
"""
|
139 |
user = super(LocalUserCreationForm, self).save(commit=False) |
140 |
user.renew_token() |
141 |
if commit:
|
142 |
user.save() |
143 |
logger.info('Created user %s', user)
|
144 |
return user
|
145 |
|
146 |
class InvitedLocalUserCreationForm(LocalUserCreationForm): |
147 |
"""
|
148 |
Extends the LocalUserCreationForm: email is readonly.
|
149 |
"""
|
150 |
class Meta: |
151 |
model = AstakosUser |
152 |
fields = ("email", "first_name", "last_name", "has_signed_terms") |
153 |
widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))} |
154 |
|
155 |
def __init__(self, *args, **kwargs): |
156 |
"""
|
157 |
Changes the order of fields, and removes the username field.
|
158 |
"""
|
159 |
super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs) |
160 |
|
161 |
#set readonly form fields
|
162 |
ro = ('email', 'username',) |
163 |
for f in ro: |
164 |
self.fields[f].widget.attrs['readonly'] = True |
165 |
|
166 |
|
167 |
def save(self, commit=True): |
168 |
user = super(InvitedLocalUserCreationForm, self).save(commit=False) |
169 |
level = user.invitation.inviter.level + 1
|
170 |
user.level = level |
171 |
user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
|
172 |
user.email_verified = True
|
173 |
if commit:
|
174 |
user.save() |
175 |
return user
|
176 |
|
177 |
class ThirdPartyUserCreationForm(forms.ModelForm): |
178 |
class Meta: |
179 |
model = AstakosUser |
180 |
fields = ("email", "first_name", "last_name", "third_party_identifier") |
181 |
widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))} |
182 |
|
183 |
def __init__(self, *args, **kwargs): |
184 |
"""
|
185 |
Changes the order of fields, and removes the username field.
|
186 |
"""
|
187 |
self.request = kwargs.get('request', None) |
188 |
if self.request: |
189 |
kwargs.pop('request')
|
190 |
super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs) |
191 |
self.fields.keyOrder = ['email', 'first_name', 'last_name', 'third_party_identifier'] |
192 |
if get_latest_terms():
|
193 |
self.fields.keyOrder.append('has_signed_terms') |
194 |
#set readonly form fields
|
195 |
ro = ["third_party_identifier", "first_name", "last_name"] |
196 |
for f in ro: |
197 |
self.fields[f].widget.attrs['readonly'] = True |
198 |
|
199 |
if 'has_signed_terms' in self.fields: |
200 |
# Overriding field label since we need to apply a link
|
201 |
# to the terms within the label
|
202 |
terms_link_html = '<a href="%s" target="_blank">%s</a>' \
|
203 |
% (reverse('latest_terms'), _("the terms")) |
204 |
self.fields['has_signed_terms'].label = \ |
205 |
mark_safe("I agree with %s" % terms_link_html)
|
206 |
|
207 |
def clean_email(self): |
208 |
email = self.cleaned_data['email'] |
209 |
if not email: |
210 |
raise forms.ValidationError(_("This field is required")) |
211 |
return email
|
212 |
|
213 |
def clean_has_signed_terms(self): |
214 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
215 |
if not has_signed_terms: |
216 |
raise forms.ValidationError(_('You have to agree with the terms')) |
217 |
return has_signed_terms
|
218 |
|
219 |
def save(self, commit=True): |
220 |
user = super(ThirdPartyUserCreationForm, self).save(commit=False) |
221 |
user.set_unusable_password() |
222 |
user.renew_token() |
223 |
user.provider = get_query(self.request).get('provider') |
224 |
if commit:
|
225 |
user.save() |
226 |
logger.info('Created user %s', user)
|
227 |
return user
|
228 |
|
229 |
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm): |
230 |
"""
|
231 |
Extends the ThirdPartyUserCreationForm: email is readonly.
|
232 |
"""
|
233 |
def __init__(self, *args, **kwargs): |
234 |
"""
|
235 |
Changes the order of fields, and removes the username field.
|
236 |
"""
|
237 |
super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs) |
238 |
|
239 |
#set readonly form fields
|
240 |
ro = ('email',)
|
241 |
for f in ro: |
242 |
self.fields[f].widget.attrs['readonly'] = True |
243 |
|
244 |
def save(self, commit=True): |
245 |
user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False) |
246 |
level = user.invitation.inviter.level + 1
|
247 |
user.level = level |
248 |
user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
|
249 |
user.email_verified = True
|
250 |
if commit:
|
251 |
user.save() |
252 |
return user
|
253 |
|
254 |
class ShibbolethUserCreationForm(ThirdPartyUserCreationForm): |
255 |
def clean_email(self): |
256 |
email = self.cleaned_data['email'] |
257 |
for user in AstakosUser.objects.filter(email = email): |
258 |
if user.provider == 'shibboleth': |
259 |
raise forms.ValidationError(_("This email is already associated with another shibboleth account.")) |
260 |
super(ShibbolethUserCreationForm, self).clean_email() |
261 |
return email
|
262 |
|
263 |
class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, InvitedThirdPartyUserCreationForm): |
264 |
pass
|
265 |
|
266 |
class LoginForm(AuthenticationForm): |
267 |
username = forms.EmailField(label=_("Email"))
|
268 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
269 |
recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
|
270 |
|
271 |
def __init__(self, *args, **kwargs): |
272 |
was_limited = kwargs.get('was_limited', False) |
273 |
request = kwargs.get('request', None) |
274 |
if request:
|
275 |
self.ip = request.META.get('REMOTE_ADDR', |
276 |
request.META.get('HTTP_X_REAL_IP', None)) |
277 |
|
278 |
t = ('request', 'was_limited') |
279 |
for elem in t: |
280 |
if elem in kwargs.keys(): |
281 |
kwargs.pop(elem) |
282 |
super(LoginForm, self).__init__(*args, **kwargs) |
283 |
|
284 |
self.fields.keyOrder = ['username', 'password'] |
285 |
if was_limited and RECAPTCHA_ENABLED: |
286 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
287 |
'recaptcha_response_field',])
|
288 |
|
289 |
def clean_recaptcha_response_field(self): |
290 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
291 |
self.validate_captcha()
|
292 |
return self.cleaned_data['recaptcha_response_field'] |
293 |
|
294 |
def clean_recaptcha_challenge_field(self): |
295 |
if 'recaptcha_response_field' in self.cleaned_data: |
296 |
self.validate_captcha()
|
297 |
return self.cleaned_data['recaptcha_challenge_field'] |
298 |
|
299 |
def validate_captcha(self): |
300 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
301 |
rrf = self.cleaned_data['recaptcha_response_field'] |
302 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
303 |
if not check.is_valid: |
304 |
raise forms.ValidationError(_('You have not entered the correct words')) |
305 |
|
306 |
class ProfileForm(forms.ModelForm): |
307 |
"""
|
308 |
Subclass of ``ModelForm`` for permiting user to edit his/her profile.
|
309 |
Most of the fields are readonly since the user is not allowed to change them.
|
310 |
|
311 |
The class defines a save method which sets ``is_verified`` to True so as the user
|
312 |
during the next login will not to be redirected to profile page.
|
313 |
"""
|
314 |
renew = forms.BooleanField(label='Renew token', required=False) |
315 |
|
316 |
class Meta: |
317 |
model = AstakosUser |
318 |
fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires') |
319 |
|
320 |
def __init__(self, *args, **kwargs): |
321 |
super(ProfileForm, self).__init__(*args, **kwargs) |
322 |
instance = getattr(self, 'instance', None) |
323 |
ro_fields = ('email', 'auth_token', 'auth_token_expires') |
324 |
if instance and instance.id: |
325 |
for field in ro_fields: |
326 |
self.fields[field].widget.attrs['readonly'] = True |
327 |
|
328 |
def save(self, commit=True): |
329 |
user = super(ProfileForm, self).save(commit=False) |
330 |
user.is_verified = True
|
331 |
if self.cleaned_data.get('renew'): |
332 |
user.renew_token() |
333 |
if commit:
|
334 |
user.save() |
335 |
return user
|
336 |
|
337 |
class FeedbackForm(forms.Form): |
338 |
"""
|
339 |
Form for writing feedback.
|
340 |
"""
|
341 |
feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
|
342 |
feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
|
343 |
required=False)
|
344 |
|
345 |
class SendInvitationForm(forms.Form): |
346 |
"""
|
347 |
Form for sending an invitations
|
348 |
"""
|
349 |
|
350 |
email = forms.EmailField(required = True, label = 'Email address') |
351 |
first_name = forms.EmailField(label = 'First name')
|
352 |
last_name = forms.EmailField(label = 'Last name')
|
353 |
|
354 |
class ExtendedPasswordResetForm(PasswordResetForm): |
355 |
"""
|
356 |
Extends PasswordResetForm by overriding save method:
|
357 |
passes a custom from_email in send_mail.
|
358 |
|
359 |
Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
|
360 |
accepts a from_email argument.
|
361 |
"""
|
362 |
def clean_email(self): |
363 |
email = super(ExtendedPasswordResetForm, self).clean_email() |
364 |
try:
|
365 |
user = AstakosUser.objects.get(email=email, is_active=True)
|
366 |
if not user.has_usable_password(): |
367 |
raise forms.ValidationError(_("This account has not a usable password.")) |
368 |
except AstakosUser.DoesNotExist, e:
|
369 |
raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?')) |
370 |
return email
|
371 |
|
372 |
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', |
373 |
use_https=False, token_generator=default_token_generator, request=None): |
374 |
"""
|
375 |
Generates a one-use only link for resetting password and sends to the user.
|
376 |
"""
|
377 |
for user in self.users_cache: |
378 |
url = reverse('django.contrib.auth.views.password_reset_confirm',
|
379 |
kwargs={'uidb36':int_to_base36(user.id),
|
380 |
'token':token_generator.make_token(user)})
|
381 |
url = request.build_absolute_uri(url) |
382 |
t = loader.get_template(email_template_name) |
383 |
c = { |
384 |
'email': user.email,
|
385 |
'url': url,
|
386 |
'site_name': SITENAME,
|
387 |
'user': user,
|
388 |
'baseurl': request.build_absolute_uri(),
|
389 |
'support': DEFAULT_CONTACT_EMAIL
|
390 |
} |
391 |
from_email = DEFAULT_FROM_EMAIL |
392 |
send_mail(_("Password reset on %s alpha2 testing") % SITENAME,
|
393 |
t.render(Context(c)), from_email, [user.email]) |
394 |
|
395 |
class SignApprovalTermsForm(forms.ModelForm): |
396 |
class Meta: |
397 |
model = AstakosUser |
398 |
fields = ("has_signed_terms",)
|
399 |
|
400 |
def __init__(self, *args, **kwargs): |
401 |
super(SignApprovalTermsForm, self).__init__(*args, **kwargs) |
402 |
|
403 |
def clean_has_signed_terms(self): |
404 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
405 |
if not has_signed_terms: |
406 |
raise forms.ValidationError(_('You have to agree with the terms')) |
407 |
return has_signed_terms
|
408 |
|
409 |
class InvitationForm(forms.ModelForm): |
410 |
username = forms.EmailField(label=_("Email"))
|
411 |
|
412 |
def __init__(self, *args, **kwargs): |
413 |
super(InvitationForm, self).__init__(*args, **kwargs) |
414 |
|
415 |
class Meta: |
416 |
model = Invitation |
417 |
fields = ('username', 'realname') |
418 |
|
419 |
def clean_username(self): |
420 |
username = self.cleaned_data['username'] |
421 |
try:
|
422 |
Invitation.objects.get(username = username) |
423 |
raise forms.ValidationError(_('There is already invitation for this email.')) |
424 |
except Invitation.DoesNotExist:
|
425 |
pass
|
426 |
return username
|