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, 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
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
52 # since Django 1.4 use django.core.urlresolvers.reverse_lazy instead
53 from astakos.im.util import reverse_lazy, reserved_email, get_query
56 import recaptcha.client.captcha as captcha
58 logger = logging.getLogger(__name__)
60 class LocalUserCreationForm(UserCreationForm):
62 Extends the built in UserCreationForm in several ways:
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.
68 recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
69 recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
73 fields = ("email", "first_name", "last_name", "has_signed_terms", "has_signed_terms")
75 def __init__(self, *args, **kwargs):
77 Changes the order of fields, and removes the username field.
79 request = kwargs.get('request', None)
82 self.ip = request.META.get('REMOTE_ADDR',
83 request.META.get('HTTP_X_REAL_IP', None))
85 super(LocalUserCreationForm, self).__init__(*args, **kwargs)
86 self.fields.keyOrder = ['email', 'first_name', 'last_name',
87 'password1', 'password2']
88 if get_latest_terms():
89 self.fields.keyOrder.append('has_signed_terms')
91 self.fields.keyOrder.extend(['recaptcha_challenge_field',
92 'recaptcha_response_field',])
94 if 'has_signed_terms' in self.fields:
95 # Overriding field label since we need to apply a link
96 # to the terms within the label
97 terms_link_html = '<a href="%s" target="_blank">%s</a>' \
98 % (reverse('latest_terms'), _("the terms"))
99 self.fields['has_signed_terms'].label = \
100 mark_safe("I agree with %s" % terms_link_html)
102 def clean_email(self):
103 email = self.cleaned_data['email']
105 raise forms.ValidationError(_("This field is required"))
106 if reserved_email(email):
107 raise forms.ValidationError(_("This email is already used"))
110 def clean_has_signed_terms(self):
111 has_signed_terms = self.cleaned_data['has_signed_terms']
112 if not has_signed_terms:
113 raise forms.ValidationError(_('You have to agree with the terms'))
114 return has_signed_terms
116 def clean_recaptcha_response_field(self):
117 if 'recaptcha_challenge_field' in self.cleaned_data:
118 self.validate_captcha()
119 return self.cleaned_data['recaptcha_response_field']
121 def clean_recaptcha_challenge_field(self):
122 if 'recaptcha_response_field' in self.cleaned_data:
123 self.validate_captcha()
124 return self.cleaned_data['recaptcha_challenge_field']
126 def validate_captcha(self):
127 rcf = self.cleaned_data['recaptcha_challenge_field']
128 rrf = self.cleaned_data['recaptcha_response_field']
129 check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
130 if not check.is_valid:
131 raise forms.ValidationError(_('You have not entered the correct words'))
133 def save(self, commit=True):
135 Saves the email, first_name and last_name properties, after the normal
136 save behavior is complete.
138 user = super(LocalUserCreationForm, self).save(commit=False)
142 logger.info('Created user %s', user)
145 class InvitedLocalUserCreationForm(LocalUserCreationForm):
147 Extends the LocalUserCreationForm: email is readonly.
151 fields = ("email", "first_name", "last_name", "has_signed_terms")
153 def __init__(self, *args, **kwargs):
155 Changes the order of fields, and removes the username field.
157 super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs)
159 #set readonly form fields
160 ro = ('email', 'username',)
162 self.fields[f].widget.attrs['readonly'] = True
165 def save(self, commit=True):
166 user = super(InvitedLocalUserCreationForm, self).save(commit=False)
167 level = user.invitation.inviter.level + 1
169 user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
170 user.email_verified = True
175 class ThirdPartyUserCreationForm(forms.ModelForm):
178 fields = ("email", "first_name", "last_name", "third_party_identifier", "has_signed_terms")
180 def __init__(self, *args, **kwargs):
182 Changes the order of fields, and removes the username field.
184 self.request = kwargs.get('request', None)
186 kwargs.pop('request')
187 super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
188 self.fields.keyOrder = ['email', 'first_name', 'last_name', 'third_party_identifier']
189 if get_latest_terms():
190 self.fields.keyOrder.append('has_signed_terms')
191 #set readonly form fields
192 ro = ["third_party_identifier", "first_name", "last_name"]
194 self.fields[f].widget.attrs['readonly'] = True
196 if 'has_signed_terms' in self.fields:
197 # Overriding field label since we need to apply a link
198 # to the terms within the label
199 terms_link_html = '<a href="%s" target="_blank">%s</a>' \
200 % (reverse('latest_terms'), _("the terms"))
201 self.fields['has_signed_terms'].label = \
202 mark_safe("I agree with %s" % terms_link_html)
204 def clean_email(self):
205 email = self.cleaned_data['email']
207 raise forms.ValidationError(_("This field is required"))
210 def clean_has_signed_terms(self):
211 has_signed_terms = self.cleaned_data['has_signed_terms']
212 if not has_signed_terms:
213 raise forms.ValidationError(_('You have to agree with the terms'))
214 return has_signed_terms
216 def save(self, commit=True):
217 user = super(ThirdPartyUserCreationForm, self).save(commit=False)
218 user.set_unusable_password()
220 user.provider = get_query(self.request).get('provider')
223 logger.info('Created user %s', user)
226 class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
228 Extends the ThirdPartyUserCreationForm: email is readonly.
230 def __init__(self, *args, **kwargs):
232 Changes the order of fields, and removes the username field.
234 super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
236 #set readonly form fields
239 self.fields[f].widget.attrs['readonly'] = True
241 def save(self, commit=True):
242 user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False)
243 level = user.invitation.inviter.level + 1
245 user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
246 user.email_verified = True
251 class ShibbolethUserCreationForm(ThirdPartyUserCreationForm):
252 def clean_email(self):
253 email = self.cleaned_data['email']
254 for user in AstakosUser.objects.filter(email = email):
255 if user.provider == 'shibboleth':
256 raise forms.ValidationError(_("This email is already associated with another shibboleth account."))
257 super(ShibbolethUserCreationForm, self).clean_email()
260 class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, InvitedThirdPartyUserCreationForm):
263 class LoginForm(AuthenticationForm):
264 username = forms.EmailField(label=_("Email"))
265 recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
266 recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
268 def __init__(self, *args, **kwargs):
269 was_limited = kwargs.get('was_limited', False)
270 request = kwargs.get('request', None)
272 self.ip = request.META.get('REMOTE_ADDR',
273 request.META.get('HTTP_X_REAL_IP', None))
275 t = ('request', 'was_limited')
277 if elem in kwargs.keys():
279 super(LoginForm, self).__init__(*args, **kwargs)
281 self.fields.keyOrder = ['username', 'password']
282 if was_limited and RECAPTCHA_ENABLED:
283 self.fields.keyOrder.extend(['recaptcha_challenge_field',
284 'recaptcha_response_field',])
286 def clean_recaptcha_response_field(self):
287 if 'recaptcha_challenge_field' in self.cleaned_data:
288 self.validate_captcha()
289 return self.cleaned_data['recaptcha_response_field']
291 def clean_recaptcha_challenge_field(self):
292 if 'recaptcha_response_field' in self.cleaned_data:
293 self.validate_captcha()
294 return self.cleaned_data['recaptcha_challenge_field']
296 def validate_captcha(self):
297 rcf = self.cleaned_data['recaptcha_challenge_field']
298 rrf = self.cleaned_data['recaptcha_response_field']
299 check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
300 if not check.is_valid:
301 raise forms.ValidationError(_('You have not entered the correct words'))
303 class ProfileForm(forms.ModelForm):
305 Subclass of ``ModelForm`` for permiting user to edit his/her profile.
306 Most of the fields are readonly since the user is not allowed to change them.
308 The class defines a save method which sets ``is_verified`` to True so as the user
309 during the next login will not to be redirected to profile page.
311 renew = forms.BooleanField(label='Renew token', required=False)
315 fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires')
317 def __init__(self, *args, **kwargs):
318 super(ProfileForm, self).__init__(*args, **kwargs)
319 instance = getattr(self, 'instance', None)
320 ro_fields = ('email', 'auth_token', 'auth_token_expires')
321 if instance and instance.id:
322 for field in ro_fields:
323 self.fields[field].widget.attrs['readonly'] = True
325 def save(self, commit=True):
326 user = super(ProfileForm, self).save(commit=False)
327 user.is_verified = True
328 if self.cleaned_data.get('renew'):
334 class FeedbackForm(forms.Form):
336 Form for writing feedback.
338 feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
339 feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
342 class SendInvitationForm(forms.Form):
344 Form for sending an invitations
347 email = forms.EmailField(required = True, label = 'Email address')
348 first_name = forms.EmailField(label = 'First name')
349 last_name = forms.EmailField(label = 'Last name')
351 class ExtendedPasswordResetForm(PasswordResetForm):
353 Extends PasswordResetForm by overriding save method:
354 passes a custom from_email in send_mail.
356 Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
357 accepts a from_email argument.
359 def clean_email(self):
360 email = super(ExtendedPasswordResetForm, self).clean_email()
362 user = AstakosUser.objects.get(email=email, is_active=True)
363 if not user.has_usable_password():
364 raise forms.ValidationError(_("This account has not a usable password."))
365 except AstakosUser.DoesNotExist, e:
366 raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?'))
369 def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
370 use_https=False, token_generator=default_token_generator, request=None):
372 Generates a one-use only link for resetting password and sends to the user.
374 for user in self.users_cache:
375 url = reverse('django.contrib.auth.views.password_reset_confirm',
376 kwargs={'uidb36':int_to_base36(user.id),
377 'token':token_generator.make_token(user)})
378 url = request.build_absolute_uri(url)
379 t = loader.get_template(email_template_name)
383 'site_name': SITENAME,
385 'baseurl': request.build_absolute_uri(),
386 'support': DEFAULT_CONTACT_EMAIL
388 from_email = DEFAULT_FROM_EMAIL
389 send_mail(_("Password reset on %s alpha2 testing") % SITENAME,
390 t.render(Context(c)), from_email, [user.email])
392 class SignApprovalTermsForm(forms.ModelForm):
395 fields = ("has_signed_terms",)
397 def __init__(self, *args, **kwargs):
398 super(SignApprovalTermsForm, self).__init__(*args, **kwargs)
400 def clean_has_signed_terms(self):
401 has_signed_terms = self.cleaned_data['has_signed_terms']
402 if not has_signed_terms:
403 raise forms.ValidationError(_('You have to agree with the terms'))
404 return has_signed_terms
406 class InvitationForm(forms.ModelForm):
407 username = forms.EmailField(label=_("Email"))
409 def __init__(self, *args, **kwargs):
410 super(InvitationForm, self).__init__(*args, **kwargs)
414 fields = ('username', 'realname')
416 def clean_username(self):
417 username = self.cleaned_data['username']
419 Invitation.objects.get(username = username)
420 raise forms.ValidationError(_('There is already invitation for this email.'))
421 except Invitation.DoesNotExist: