1 # Copyright 2011-2012 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
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.
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.
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
36 from django import forms
37 from django.utils.translation import ugettext as _
38 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, \
39 PasswordResetForm, PasswordChangeForm
40 from django.core.mail import send_mail
41 from django.contrib.auth.tokens import default_token_generator
42 from django.template import Context, loader
43 from django.utils.http import int_to_base36
44 from django.core.urlresolvers import reverse
45 from django.utils.functional import lazy
46 from django.utils.safestring import mark_safe
47 from django.contrib import messages
48 from django.utils.encoding import smart_str
50 from astakos.im.models import AstakosUser, Invitation, get_latest_terms, EmailChange
51 from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, \
52 BASEURL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL, \
53 RECAPTCHA_ENABLED, LOGGING_LEVEL
54 from astakos.im.widgets import DummyWidget, RecaptchaWidget
55 from astakos.im.functions import send_change_email
57 # since Django 1.4 use django.core.urlresolvers.reverse_lazy instead
58 from astakos.im.util import reverse_lazy, reserved_email, get_query
62 import recaptcha.client.captcha as captcha
63 from random import random
65 logger = logging.getLogger(__name__)
67 class LocalUserCreationForm(UserCreationForm):
69 Extends the built in UserCreationForm in several ways:
71 * Adds email, first_name, last_name, recaptcha_challenge_field, recaptcha_response_field field.
72 * The username field isn't visible and it is assigned a generated id.
73 * User created is not active.
75 recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
76 recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
80 fields = ("email", "first_name", "last_name", "has_signed_terms", "has_signed_terms")
82 def __init__(self, *args, **kwargs):
84 Changes the order of fields, and removes the username field.
86 request = kwargs.get('request', None)
89 self.ip = request.META.get('REMOTE_ADDR',
90 request.META.get('HTTP_X_REAL_IP', None))
92 super(LocalUserCreationForm, self).__init__(*args, **kwargs)
93 self.fields.keyOrder = ['email', 'first_name', 'last_name',
94 'password1', 'password2']
97 self.fields.keyOrder.extend(['recaptcha_challenge_field',
98 'recaptcha_response_field',])
99 if get_latest_terms():
100 self.fields.keyOrder.append('has_signed_terms')
102 if 'has_signed_terms' in self.fields:
103 # Overriding field label since we need to apply a link
104 # to the terms within the label
105 terms_link_html = '<a href="%s" target="_blank">%s</a>' \
106 % (reverse('latest_terms'), _("the terms"))
107 self.fields['has_signed_terms'].label = \
108 mark_safe("I agree with %s" % terms_link_html)
110 def clean_email(self):
111 email = self.cleaned_data['email']
113 raise forms.ValidationError(_("This field is required"))
114 if reserved_email(email):
115 raise forms.ValidationError(_("This email is already used"))
118 def clean_has_signed_terms(self):
119 has_signed_terms = self.cleaned_data['has_signed_terms']
120 if not has_signed_terms:
121 raise forms.ValidationError(_('You have to agree with the terms'))
122 return has_signed_terms
124 def clean_recaptcha_response_field(self):
125 if 'recaptcha_challenge_field' in self.cleaned_data:
126 self.validate_captcha()
127 return self.cleaned_data['recaptcha_response_field']
129 def clean_recaptcha_challenge_field(self):
130 if 'recaptcha_response_field' in self.cleaned_data:
131 self.validate_captcha()
132 return self.cleaned_data['recaptcha_challenge_field']
134 def validate_captcha(self):
135 rcf = self.cleaned_data['recaptcha_challenge_field']
136 rrf = self.cleaned_data['recaptcha_response_field']
137 check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
138 if not check.is_valid:
139 raise forms.ValidationError(_('You have not entered the correct words'))
141 def save(self, commit=True):
143 Saves the email, first_name and last_name properties, after the normal
144 save behavior is complete.
146 user = super(LocalUserCreationForm, self).save(commit=False)
150 logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, [])
153 class InvitedLocalUserCreationForm(LocalUserCreationForm):
155 Extends the LocalUserCreationForm: email is readonly.
159 fields = ("email", "first_name", "last_name", "has_signed_terms")
161 def __init__(self, *args, **kwargs):
163 Changes the order of fields, and removes the username field.
165 super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs)
167 #set readonly form fields
168 ro = ('email', 'username',)
170 self.fields[f].widget.attrs['readonly'] = True
173 def save(self, commit=True):
174 user = super(InvitedLocalUserCreationForm, self).save(commit=False)
175 level = user.invitation.inviter.level + 1
177 user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
178 user.email_verified = True
183 class ThirdPartyUserCreationForm(forms.ModelForm):
186 fields = ("email", "first_name", "last_name", "third_party_identifier", "has_signed_terms")
188 def __init__(self, *args, **kwargs):
190 Changes the order of fields, and removes the username field.
192 self.request = kwargs.get('request', None)
194 kwargs.pop('request')
195 super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
196 self.fields.keyOrder = ['email', 'first_name', 'last_name', 'third_party_identifier']
197 if get_latest_terms():
198 self.fields.keyOrder.append('has_signed_terms')
199 #set readonly form fields
200 ro = ["third_party_identifier"]
202 self.fields[f].widget.attrs['readonly'] = True
204 if 'has_signed_terms' in self.fields:
205 # Overriding field label since we need to apply a link
206 # to the terms within the label
207 terms_link_html = '<a href="%s" target="_blank">%s</a>' \
208 % (reverse('latest_terms'), _("the terms"))
209 self.fields['has_signed_terms'].label = \
210 mark_safe("I agree with %s" % terms_link_html)
212 def clean_email(self):
213 email = self.cleaned_data['email']
215 raise forms.ValidationError(_("This field is required"))
218 def clean_has_signed_terms(self):
219 has_signed_terms = self.cleaned_data['has_signed_terms']
220 if not has_signed_terms:
221 raise forms.ValidationError(_('You have to agree with the terms'))
222 return has_signed_terms
224 def save(self, commit=True):
225 user = super(ThirdPartyUserCreationForm, self).save(commit=False)
226 user.set_unusable_password()
228 user.provider = get_query(self.request).get('provider')
231 logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, [])
234 class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
236 Extends the ThirdPartyUserCreationForm: email is readonly.
238 def __init__(self, *args, **kwargs):
240 Changes the order of fields, and removes the username field.
242 super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
244 #set readonly form fields
247 self.fields[f].widget.attrs['readonly'] = True
249 def save(self, commit=True):
250 user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False)
251 level = user.invitation.inviter.level + 1
253 user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
254 user.email_verified = True
259 class ShibbolethUserCreationForm(ThirdPartyUserCreationForm):
260 additional_email = forms.CharField(widget=forms.HiddenInput(), label='', required = False)
262 def __init__(self, *args, **kwargs):
263 super(ShibbolethUserCreationForm, self).__init__(*args, **kwargs)
264 self.fields.keyOrder.append('additional_email')
265 # copy email value to additional_mail in case user will change it
267 field = self.fields[name]
268 self.initial['additional_email'] = self.initial.get(name, field.initial)
270 def clean_email(self):
271 email = self.cleaned_data['email']
272 for user in AstakosUser.objects.filter(email = email):
273 if user.provider == 'shibboleth':
274 raise forms.ValidationError(_("This email is already associated with another shibboleth account."))
275 elif not user.is_active:
276 raise forms.ValidationError(_("This email is already associated with an inactive account. \
277 You need to wait to be activated before being able to switch to a shibboleth account."))
278 super(ShibbolethUserCreationForm, self).clean_email()
281 class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, InvitedThirdPartyUserCreationForm):
284 class LoginForm(AuthenticationForm):
285 username = forms.EmailField(label=_("Email"))
286 recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
287 recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
289 def __init__(self, *args, **kwargs):
290 was_limited = kwargs.get('was_limited', False)
291 request = kwargs.get('request', None)
293 self.ip = request.META.get('REMOTE_ADDR',
294 request.META.get('HTTP_X_REAL_IP', None))
296 t = ('request', 'was_limited')
298 if elem in kwargs.keys():
300 super(LoginForm, self).__init__(*args, **kwargs)
302 self.fields.keyOrder = ['username', 'password']
303 if was_limited and RECAPTCHA_ENABLED:
304 self.fields.keyOrder.extend(['recaptcha_challenge_field',
305 'recaptcha_response_field',])
307 def clean_recaptcha_response_field(self):
308 if 'recaptcha_challenge_field' in self.cleaned_data:
309 self.validate_captcha()
310 return self.cleaned_data['recaptcha_response_field']
312 def clean_recaptcha_challenge_field(self):
313 if 'recaptcha_response_field' in self.cleaned_data:
314 self.validate_captcha()
315 return self.cleaned_data['recaptcha_challenge_field']
317 def validate_captcha(self):
318 rcf = self.cleaned_data['recaptcha_challenge_field']
319 rrf = self.cleaned_data['recaptcha_response_field']
320 check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
321 if not check.is_valid:
322 raise forms.ValidationError(_('You have not entered the correct words'))
325 super(LoginForm, self).clean()
326 if self.user_cache and self.user_cache.provider not in ('local', ''):
327 raise forms.ValidationError(_('Local login is not the current authentication method for this account.'))
328 return self.cleaned_data
330 class ProfileForm(forms.ModelForm):
332 Subclass of ``ModelForm`` for permiting user to edit his/her profile.
333 Most of the fields are readonly since the user is not allowed to change them.
335 The class defines a save method which sets ``is_verified`` to True so as the user
336 during the next login will not to be redirected to profile page.
338 renew = forms.BooleanField(label='Renew token', required=False)
342 fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires')
344 def __init__(self, *args, **kwargs):
345 super(ProfileForm, self).__init__(*args, **kwargs)
346 instance = getattr(self, 'instance', None)
347 ro_fields = ('email', 'auth_token', 'auth_token_expires')
348 if instance and instance.id:
349 for field in ro_fields:
350 self.fields[field].widget.attrs['readonly'] = True
352 def save(self, commit=True):
353 user = super(ProfileForm, self).save(commit=False)
354 user.is_verified = True
355 if self.cleaned_data.get('renew'):
361 class FeedbackForm(forms.Form):
363 Form for writing feedback.
365 feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
366 feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
369 class SendInvitationForm(forms.Form):
371 Form for sending an invitations
374 email = forms.EmailField(required = True, label = 'Email address')
375 first_name = forms.EmailField(label = 'First name')
376 last_name = forms.EmailField(label = 'Last name')
378 class ExtendedPasswordResetForm(PasswordResetForm):
380 Extends PasswordResetForm by overriding save method:
381 passes a custom from_email in send_mail.
383 Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
384 accepts a from_email argument.
386 def clean_email(self):
387 email = super(ExtendedPasswordResetForm, self).clean_email()
389 user = AstakosUser.objects.get(email=email, is_active=True)
390 if not user.has_usable_password():
391 raise forms.ValidationError(_("This account has not a usable password."))
392 except AstakosUser.DoesNotExist, e:
393 raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?'))
396 def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
397 use_https=False, token_generator=default_token_generator, request=None):
399 Generates a one-use only link for resetting password and sends to the user.
401 for user in self.users_cache:
402 url = reverse('django.contrib.auth.views.password_reset_confirm',
403 kwargs={'uidb36':int_to_base36(user.id),
404 'token':token_generator.make_token(user)})
405 url = urljoin(BASEURL, url)
406 t = loader.get_template(email_template_name)
410 'site_name': SITENAME,
413 'support': DEFAULT_CONTACT_EMAIL
415 from_email = DEFAULT_FROM_EMAIL
416 send_mail(_("Password reset on %s alpha2 testing") % SITENAME,
417 t.render(Context(c)), from_email, [user.email])
419 class EmailChangeForm(forms.ModelForm):
422 fields = ('new_email_address',)
424 def clean_new_email_address(self):
425 addr = self.cleaned_data['new_email_address']
426 if AstakosUser.objects.filter(email__iexact=addr):
427 raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
430 def save(self, email_template_name, request, commit=True):
431 ec = super(EmailChangeForm, self).save(commit=False)
432 ec.user = request.user
433 activation_key = hashlib.sha1(str(random()) + smart_str(ec.new_email_address))
434 ec.activation_key=activation_key.hexdigest()
437 send_change_email(ec, request, email_template_name=email_template_name)
439 class SignApprovalTermsForm(forms.ModelForm):
442 fields = ("has_signed_terms",)
444 def __init__(self, *args, **kwargs):
445 super(SignApprovalTermsForm, self).__init__(*args, **kwargs)
447 def clean_has_signed_terms(self):
448 has_signed_terms = self.cleaned_data['has_signed_terms']
449 if not has_signed_terms:
450 raise forms.ValidationError(_('You have to agree with the terms'))
451 return has_signed_terms
453 class InvitationForm(forms.ModelForm):
454 username = forms.EmailField(label=_("Email"))
456 def __init__(self, *args, **kwargs):
457 super(InvitationForm, self).__init__(*args, **kwargs)
461 fields = ('username', 'realname')
463 def clean_username(self):
464 username = self.cleaned_data['username']
466 Invitation.objects.get(username = username)
467 raise forms.ValidationError(_('There is already invitation for this email.'))
468 except Invitation.DoesNotExist:
472 class ExtendedPasswordChangeForm(PasswordChangeForm):
474 Extends PasswordChangeForm by enabling user
475 to optionally renew also the token.
477 renew = forms.BooleanField(label='Renew token', required=False)
479 def __init__(self, user, *args, **kwargs):
480 super(ExtendedPasswordChangeForm, self).__init__(user, *args, **kwargs)
482 def save(self, commit=True):
483 user = super(ExtendedPasswordChangeForm, self).save(commit=False)
484 if self.cleaned_data.get('renew'):