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
49 from django.forms.extras.widgets import SelectDateWidget
50 from django.db.models import Q
52 from astakos.im.models import *
53 from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, \
54 BASEURL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL, \
55 RECAPTCHA_ENABLED, LOGGING_LEVEL
56 from astakos.im.widgets import DummyWidget, RecaptchaWidget
57 from astakos.im.functions import send_change_email
59 # since Django 1.4 use django.core.urlresolvers.reverse_lazy instead
60 from astakos.im.util import reverse_lazy, reserved_email, get_query
64 import recaptcha.client.captcha as captcha
65 from random import random
67 logger = logging.getLogger(__name__)
69 class LocalUserCreationForm(UserCreationForm):
71 Extends the built in UserCreationForm in several ways:
73 * Adds email, first_name, last_name, recaptcha_challenge_field, recaptcha_response_field field.
74 * The username field isn't visible and it is assigned a generated id.
75 * User created is not active.
77 recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
78 recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
82 fields = ("email", "first_name", "last_name", "has_signed_terms", "has_signed_terms")
84 def __init__(self, *args, **kwargs):
86 Changes the order of fields, and removes the username field.
88 request = kwargs.get('request', None)
91 self.ip = request.META.get('REMOTE_ADDR',
92 request.META.get('HTTP_X_REAL_IP', None))
94 super(LocalUserCreationForm, self).__init__(*args, **kwargs)
95 self.fields.keyOrder = ['email', 'first_name', 'last_name',
96 'password1', 'password2']
99 self.fields.keyOrder.extend(['recaptcha_challenge_field',
100 'recaptcha_response_field',])
101 if get_latest_terms():
102 self.fields.keyOrder.append('has_signed_terms')
104 if 'has_signed_terms' in self.fields:
105 # Overriding field label since we need to apply a link
106 # to the terms within the label
107 terms_link_html = '<a href="%s" target="_blank">%s</a>' \
108 % (reverse('latest_terms'), _("the terms"))
109 self.fields['has_signed_terms'].label = \
110 mark_safe("I agree with %s" % terms_link_html)
112 def clean_email(self):
113 email = self.cleaned_data['email']
115 raise forms.ValidationError(_("This field is required"))
116 if reserved_email(email):
117 raise forms.ValidationError(_("This email is already used"))
120 def clean_has_signed_terms(self):
121 has_signed_terms = self.cleaned_data['has_signed_terms']
122 if not has_signed_terms:
123 raise forms.ValidationError(_('You have to agree with the terms'))
124 return has_signed_terms
126 def clean_recaptcha_response_field(self):
127 if 'recaptcha_challenge_field' in self.cleaned_data:
128 self.validate_captcha()
129 return self.cleaned_data['recaptcha_response_field']
131 def clean_recaptcha_challenge_field(self):
132 if 'recaptcha_response_field' in self.cleaned_data:
133 self.validate_captcha()
134 return self.cleaned_data['recaptcha_challenge_field']
136 def validate_captcha(self):
137 rcf = self.cleaned_data['recaptcha_challenge_field']
138 rrf = self.cleaned_data['recaptcha_response_field']
139 check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
140 if not check.is_valid:
141 raise forms.ValidationError(_('You have not entered the correct words'))
143 def save(self, commit=True):
145 Saves the email, first_name and last_name properties, after the normal
146 save behavior is complete.
148 user = super(LocalUserCreationForm, self).save(commit=False)
152 logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, [])
155 class InvitedLocalUserCreationForm(LocalUserCreationForm):
157 Extends the LocalUserCreationForm: email is readonly.
161 fields = ("email", "first_name", "last_name", "has_signed_terms")
163 def __init__(self, *args, **kwargs):
165 Changes the order of fields, and removes the username field.
167 super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs)
169 #set readonly form fields
170 ro = ('email', 'username',)
172 self.fields[f].widget.attrs['readonly'] = True
175 def save(self, commit=True):
176 user = super(InvitedLocalUserCreationForm, self).save(commit=False)
177 level = user.invitation.inviter.level + 1
179 user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
180 user.email_verified = True
185 class ThirdPartyUserCreationForm(forms.ModelForm):
188 fields = ("email", "first_name", "last_name", "third_party_identifier", "has_signed_terms")
190 def __init__(self, *args, **kwargs):
192 Changes the order of fields, and removes the username field.
194 self.request = kwargs.get('request', None)
196 kwargs.pop('request')
197 super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
198 self.fields.keyOrder = ['email', 'first_name', 'last_name', 'third_party_identifier']
199 if get_latest_terms():
200 self.fields.keyOrder.append('has_signed_terms')
201 #set readonly form fields
202 ro = ["third_party_identifier"]
204 self.fields[f].widget.attrs['readonly'] = True
206 if 'has_signed_terms' in self.fields:
207 # Overriding field label since we need to apply a link
208 # to the terms within the label
209 terms_link_html = '<a href="%s" target="_blank">%s</a>' \
210 % (reverse('latest_terms'), _("the terms"))
211 self.fields['has_signed_terms'].label = \
212 mark_safe("I agree with %s" % terms_link_html)
214 def clean_email(self):
215 email = self.cleaned_data['email']
217 raise forms.ValidationError(_("This field is required"))
220 def clean_has_signed_terms(self):
221 has_signed_terms = self.cleaned_data['has_signed_terms']
222 if not has_signed_terms:
223 raise forms.ValidationError(_('You have to agree with the terms'))
224 return has_signed_terms
226 def save(self, commit=True):
227 user = super(ThirdPartyUserCreationForm, self).save(commit=False)
228 user.set_unusable_password()
230 user.provider = get_query(self.request).get('provider')
233 logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, [])
236 class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
238 Extends the ThirdPartyUserCreationForm: email is readonly.
240 def __init__(self, *args, **kwargs):
242 Changes the order of fields, and removes the username field.
244 super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
246 #set readonly form fields
249 self.fields[f].widget.attrs['readonly'] = True
251 def save(self, commit=True):
252 user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False)
253 level = user.invitation.inviter.level + 1
255 user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
256 user.email_verified = True
261 class ShibbolethUserCreationForm(ThirdPartyUserCreationForm):
262 additional_email = forms.CharField(widget=forms.HiddenInput(), label='', required = False)
264 def __init__(self, *args, **kwargs):
265 super(ShibbolethUserCreationForm, self).__init__(*args, **kwargs)
266 self.fields.keyOrder.append('additional_email')
267 # copy email value to additional_mail in case user will change it
269 field = self.fields[name]
270 self.initial['additional_email'] = self.initial.get(name, field.initial)
272 def clean_email(self):
273 email = self.cleaned_data['email']
274 for user in AstakosUser.objects.filter(email = email):
275 if user.provider == 'shibboleth':
276 raise forms.ValidationError(_("This email is already associated with another shibboleth account."))
277 elif not user.is_active:
278 raise forms.ValidationError(_("This email is already associated with an inactive account. \
279 You need to wait to be activated before being able to switch to a shibboleth account."))
280 super(ShibbolethUserCreationForm, self).clean_email()
283 class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, InvitedThirdPartyUserCreationForm):
286 class LoginForm(AuthenticationForm):
287 username = forms.EmailField(label=_("Email"))
288 recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
289 recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
291 def __init__(self, *args, **kwargs):
292 was_limited = kwargs.get('was_limited', False)
293 request = kwargs.get('request', None)
295 self.ip = request.META.get('REMOTE_ADDR',
296 request.META.get('HTTP_X_REAL_IP', None))
298 t = ('request', 'was_limited')
300 if elem in kwargs.keys():
302 super(LoginForm, self).__init__(*args, **kwargs)
304 self.fields.keyOrder = ['username', 'password']
305 if was_limited and RECAPTCHA_ENABLED:
306 self.fields.keyOrder.extend(['recaptcha_challenge_field',
307 'recaptcha_response_field',])
309 def clean_recaptcha_response_field(self):
310 if 'recaptcha_challenge_field' in self.cleaned_data:
311 self.validate_captcha()
312 return self.cleaned_data['recaptcha_response_field']
314 def clean_recaptcha_challenge_field(self):
315 if 'recaptcha_response_field' in self.cleaned_data:
316 self.validate_captcha()
317 return self.cleaned_data['recaptcha_challenge_field']
319 def validate_captcha(self):
320 rcf = self.cleaned_data['recaptcha_challenge_field']
321 rrf = self.cleaned_data['recaptcha_response_field']
322 check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
323 if not check.is_valid:
324 raise forms.ValidationError(_('You have not entered the correct words'))
327 super(LoginForm, self).clean()
328 if self.user_cache and self.user_cache.provider not in ('local', ''):
329 raise forms.ValidationError(_('Local login is not the current authentication method for this account.'))
330 return self.cleaned_data
332 class ProfileForm(forms.ModelForm):
334 Subclass of ``ModelForm`` for permiting user to edit his/her profile.
335 Most of the fields are readonly since the user is not allowed to change them.
337 The class defines a save method which sets ``is_verified`` to True so as the user
338 during the next login will not to be redirected to profile page.
340 renew = forms.BooleanField(label='Renew token', required=False)
344 fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires')
346 def __init__(self, *args, **kwargs):
347 super(ProfileForm, self).__init__(*args, **kwargs)
348 instance = getattr(self, 'instance', None)
349 ro_fields = ('email', 'auth_token', 'auth_token_expires')
350 if instance and instance.id:
351 for field in ro_fields:
352 self.fields[field].widget.attrs['readonly'] = True
354 def save(self, commit=True):
355 user = super(ProfileForm, self).save(commit=False)
356 user.is_verified = True
357 if self.cleaned_data.get('renew'):
363 class FeedbackForm(forms.Form):
365 Form for writing feedback.
367 feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
368 feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
371 class SendInvitationForm(forms.Form):
373 Form for sending an invitations
376 email = forms.EmailField(required = True, label = 'Email address')
377 first_name = forms.EmailField(label = 'First name')
378 last_name = forms.EmailField(label = 'Last name')
380 class ExtendedPasswordResetForm(PasswordResetForm):
382 Extends PasswordResetForm by overriding save method:
383 passes a custom from_email in send_mail.
385 Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
386 accepts a from_email argument.
388 def clean_email(self):
389 email = super(ExtendedPasswordResetForm, self).clean_email()
391 user = AstakosUser.objects.get(email=email, is_active=True)
392 if not user.has_usable_password():
393 raise forms.ValidationError(_("This account has not a usable password."))
394 except AstakosUser.DoesNotExist, e:
395 raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?'))
398 def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
399 use_https=False, token_generator=default_token_generator, request=None):
401 Generates a one-use only link for resetting password and sends to the user.
403 for user in self.users_cache:
404 url = reverse('django.contrib.auth.views.password_reset_confirm',
405 kwargs={'uidb36':int_to_base36(user.id),
406 'token':token_generator.make_token(user)})
407 url = urljoin(BASEURL, url)
408 t = loader.get_template(email_template_name)
412 'site_name': SITENAME,
415 'support': DEFAULT_CONTACT_EMAIL
417 from_email = DEFAULT_FROM_EMAIL
418 send_mail(_("Password reset on %s alpha2 testing") % SITENAME,
419 t.render(Context(c)), from_email, [user.email])
421 class EmailChangeForm(forms.ModelForm):
424 fields = ('new_email_address',)
426 def clean_new_email_address(self):
427 addr = self.cleaned_data['new_email_address']
428 if AstakosUser.objects.filter(email__iexact=addr):
429 raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
432 def save(self, email_template_name, request, commit=True):
433 ec = super(EmailChangeForm, self).save(commit=False)
434 ec.user = request.user
435 activation_key = hashlib.sha1(str(random()) + smart_str(ec.new_email_address))
436 ec.activation_key=activation_key.hexdigest()
439 send_change_email(ec, request, email_template_name=email_template_name)
441 class SignApprovalTermsForm(forms.ModelForm):
444 fields = ("has_signed_terms",)
446 def __init__(self, *args, **kwargs):
447 super(SignApprovalTermsForm, self).__init__(*args, **kwargs)
449 def clean_has_signed_terms(self):
450 has_signed_terms = self.cleaned_data['has_signed_terms']
451 if not has_signed_terms:
452 raise forms.ValidationError(_('You have to agree with the terms'))
453 return has_signed_terms
455 class InvitationForm(forms.ModelForm):
456 username = forms.EmailField(label=_("Email"))
458 def __init__(self, *args, **kwargs):
459 super(InvitationForm, self).__init__(*args, **kwargs)
463 fields = ('username', 'realname')
465 def clean_username(self):
466 username = self.cleaned_data['username']
468 Invitation.objects.get(username = username)
469 raise forms.ValidationError(_('There is already invitation for this email.'))
470 except Invitation.DoesNotExist:
474 class ExtendedPasswordChangeForm(PasswordChangeForm):
476 Extends PasswordChangeForm by enabling user
477 to optionally renew also the token.
479 renew = forms.BooleanField(label='Renew token', required=False)
481 def __init__(self, user, *args, **kwargs):
482 super(ExtendedPasswordChangeForm, self).__init__(user, *args, **kwargs)
484 def save(self, commit=True):
485 user = super(ExtendedPasswordChangeForm, self).save(commit=False)
486 if self.cleaned_data.get('renew'):
492 def get_astakos_group_creation_form(request):
493 class AstakosGroupCreationForm(forms.ModelForm):
494 issue_date = forms.DateField(widget=SelectDateWidget(), initial=datetime.now())
495 # TODO set initial in exact one month
496 expiration_date = forms.DateField(widget=SelectDateWidget(), initial = datetime.now() + timedelta(days=30))
497 kind = forms.ModelChoiceField(queryset=GroupKind.objects.all(), empty_label=None)
498 name = forms.URLField()
503 def __init__(self, *args, **kwargs):
504 super(AstakosGroupCreationForm, self).__init__(*args, **kwargs)
505 self.fields.keyOrder = ['kind', 'name', 'desc', 'issue_date',
506 'expiration_date', 'estimated_participants',
507 'moderatation_enabled']
509 def save(self, commit=True):
510 g = super(AstakosGroupCreationForm, self).save(commit=False)
513 g.owner = [request.user]
514 g.approve_member(request.user)
517 return AstakosGroupCreationForm
519 def get_astakos_group_policy_creation_form(astakosgroup):
520 class AstakosGroupPolicyCreationForm(forms.ModelForm):
521 choices = Resource.objects.filter(~Q(astakosgroup=astakosgroup))
522 resource = forms.ModelChoiceField(queryset=choices, empty_label=None)
523 # TODO check that it does not hit the db
524 group = forms.ModelChoiceField(queryset=AstakosGroup.objects.all(), initial=astakosgroup, widget=forms.HiddenInput())
527 model = AstakosGroupQuota
529 return AstakosGroupPolicyCreationForm