Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / forms.py @ 7faeaef3

History | View | Annotate | Download (21.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

    
35
from django import forms
36
from django.utils.translation import ugettext as _
37
from django.contrib.auth.forms import (UserCreationForm, AuthenticationForm,
38
    PasswordResetForm, PasswordChangeForm
39
)
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.safestring import mark_safe
46
from django.utils.encoding import smart_str
47
from django.forms.extras.widgets import SelectDateWidget
48
from django.conf import settings
49

    
50
from astakos.im.models import (AstakosUser, EmailChange, AstakosGroup, Invitation,
51
    Membership, GroupKind, get_latest_terms
52
)
53
from astakos.im.settings import (INVITATIONS_PER_LEVEL, BASEURL, SITENAME,
54
    RECAPTCHA_PRIVATE_KEY, RECAPTCHA_ENABLED, DEFAULT_CONTACT_EMAIL,
55
    LOGGING_LEVEL
56
)
57
from astakos.im.widgets import DummyWidget, RecaptchaWidget
58
from astakos.im.functions import send_change_email
59

    
60
from astakos.im.util import reserved_email, get_query
61

    
62
import logging
63
import hashlib
64
import recaptcha.client.captcha as captcha
65
from random import random
66

    
67
logger = logging.getLogger(__name__)
68

    
69
class LocalUserCreationForm(UserCreationForm):
70
    """
71
    Extends the built in UserCreationForm in several ways:
72

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.
76
    """
77
    recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
78
    recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
79

    
80
    class Meta:
81
        model = AstakosUser
82
        fields = ("email", "first_name", "last_name", "has_signed_terms", "has_signed_terms")
83

    
84
    def __init__(self, *args, **kwargs):
85
        """
86
        Changes the order of fields, and removes the username field.
87
        """
88
        request = kwargs.get('request', None)
89
        if request:
90
            kwargs.pop('request')
91
            self.ip = request.META.get('REMOTE_ADDR',
92
                                       request.META.get('HTTP_X_REAL_IP', None))
93
        
94
        super(LocalUserCreationForm, self).__init__(*args, **kwargs)
95
        self.fields.keyOrder = ['email', 'first_name', 'last_name',
96
                                'password1', 'password2']
97

    
98
        if RECAPTCHA_ENABLED:
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')
103
            
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)
111

    
112
    def clean_email(self):
113
        email = self.cleaned_data['email']
114
        if not email:
115
            raise forms.ValidationError(_("This field is required"))
116
        if reserved_email(email):
117
            raise forms.ValidationError(_("This email is already used"))
118
        return email
119

    
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
125

    
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']
130

    
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']
135

    
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'))
142

    
143
    def save(self, commit=True):
144
        """
145
        Saves the email, first_name and last_name properties, after the normal
146
        save behavior is complete.
147
        """
148
        user = super(LocalUserCreationForm, self).save(commit=False)
149
        user.renew_token()
150
        if commit:
151
            user.save()
152
            logger.log(LOGGING_LEVEL, 'Created user %s' % user.email)
153
        return user
154

    
155
class InvitedLocalUserCreationForm(LocalUserCreationForm):
156
    """
157
    Extends the LocalUserCreationForm: email is readonly.
158
    """
159
    class Meta:
160
        model = AstakosUser
161
        fields = ("email", "first_name", "last_name", "has_signed_terms")
162

    
163
    def __init__(self, *args, **kwargs):
164
        """
165
        Changes the order of fields, and removes the username field.
166
        """
167
        super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs)
168

    
169
        #set readonly form fields
170
        ro = ('email', 'username',)
171
        for f in ro:
172
            self.fields[f].widget.attrs['readonly'] = True
173
        
174

    
175
    def save(self, commit=True):
176
        user = super(InvitedLocalUserCreationForm, self).save(commit=False)
177
        level = user.invitation.inviter.level + 1
178
        user.level = level
179
        user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
180
        user.email_verified = True
181
        if commit:
182
            user.save()
183
        return user
184

    
185
class ThirdPartyUserCreationForm(forms.ModelForm):
186
    class Meta:
187
        model = AstakosUser
188
        fields = ("email", "first_name", "last_name", "third_party_identifier", "has_signed_terms")
189
    
190
    def __init__(self, *args, **kwargs):
191
        """
192
        Changes the order of fields, and removes the username field.
193
        """
194
        self.request = kwargs.get('request', None)
195
        if self.request:
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"]
203
        for f in ro:
204
            self.fields[f].widget.attrs['readonly'] = True
205
        
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)
213
    
214
    def clean_email(self):
215
        email = self.cleaned_data['email']
216
        if not email:
217
            raise forms.ValidationError(_("This field is required"))
218
        return email
219
    
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
225
    
226
    def save(self, commit=True):
227
        user = super(ThirdPartyUserCreationForm, self).save(commit=False)
228
        user.set_unusable_password()
229
        user.renew_token()
230
        user.provider = get_query(self.request).get('provider')
231
        if commit:
232
            user.save()
233
            logger.log(LOGGING_LEVEL, 'Created user %s' % user.email)
234
        return user
235

    
236
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
237
    """
238
    Extends the ThirdPartyUserCreationForm: email is readonly.
239
    """
240
    def __init__(self, *args, **kwargs):
241
        """
242
        Changes the order of fields, and removes the username field.
243
        """
244
        super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
245

    
246
        #set readonly form fields
247
        ro = ('email',)
248
        for f in ro:
249
            self.fields[f].widget.attrs['readonly'] = True
250
    
251
    def save(self, commit=True):
252
        user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False)
253
        level = user.invitation.inviter.level + 1
254
        user.level = level
255
        user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
256
        user.email_verified = True
257
        if commit:
258
            user.save()
259
        return user
260

    
261
class ShibbolethUserCreationForm(ThirdPartyUserCreationForm):
262
    additional_email = forms.CharField(widget=forms.HiddenInput(), label='', required = False)
263
    
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
268
        name = 'email'
269
        field = self.fields[name]
270
        self.initial['additional_email'] = self.initial.get(name, field.initial)
271
    
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()
281
        return email
282

    
283
class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, InvitedThirdPartyUserCreationForm):
284
    pass
285
    
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='')
290
    
291
    def __init__(self, *args, **kwargs):
292
        was_limited = kwargs.get('was_limited', False)
293
        request = kwargs.get('request', None)
294
        if request:
295
            self.ip = request.META.get('REMOTE_ADDR',
296
                                       request.META.get('HTTP_X_REAL_IP', None))
297
        
298
        t = ('request', 'was_limited')
299
        for elem in t:
300
            if elem in kwargs.keys():
301
                kwargs.pop(elem)
302
        super(LoginForm, self).__init__(*args, **kwargs)
303
        
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',])
308
    
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']
313

    
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']
318

    
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'))
325
    
326
    def clean(self):
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
331

    
332
class ProfileForm(forms.ModelForm):
333
    """
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.
336

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.
339
    """
340
    renew = forms.BooleanField(label='Renew token', required=False)
341

    
342
    class Meta:
343
        model = AstakosUser
344
        fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires')
345

    
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
353

    
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'):
358
            user.renew_token()
359
        if commit:
360
            user.save()
361
        return user
362

    
363
class FeedbackForm(forms.Form):
364
    """
365
    Form for writing feedback.
366
    """
367
    feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
368
    feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
369
                                    required=False)
370

    
371
class SendInvitationForm(forms.Form):
372
    """
373
    Form for sending an invitations
374
    """
375

    
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')
379

    
380
class ExtendedPasswordResetForm(PasswordResetForm):
381
    """
382
    Extends PasswordResetForm by overriding save method:
383
    passes a custom from_email in send_mail.
384

385
    Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
386
    accepts a from_email argument.
387
    """
388
    def clean_email(self):
389
        email = super(ExtendedPasswordResetForm, self).clean_email()
390
        try:
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:
395
            raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?'))
396
        return email
397
    
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):
400
        """
401
        Generates a one-use only link for resetting password and sends to the user.
402
        """
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
                }
408
            )
409
            url = urljoin(BASEURL, url)
410
            t = loader.get_template(email_template_name)
411
            c = {
412
                'email': user.email,
413
                'url': url,
414
                'site_name': SITENAME,
415
                'user': user,
416
                'baseurl': BASEURL,
417
                'support': DEFAULT_CONTACT_EMAIL
418
            }
419
            from_email = settings.SERVER_EMAIL
420
            send_mail(_("Password reset on %s alpha2 testing") % SITENAME,
421
                t.render(Context(c)), from_email, [user.email])
422

    
423
class EmailChangeForm(forms.ModelForm):
424
    class Meta:
425
        model = EmailChange
426
        fields = ('new_email_address',)
427
            
428
    def clean_new_email_address(self):
429
        addr = self.cleaned_data['new_email_address']
430
        if AstakosUser.objects.filter(email__iexact=addr):
431
            raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
432
        return addr
433
    
434
    def save(self, email_template_name, request, commit=True):
435
        ec = super(EmailChangeForm, self).save(commit=False)
436
        ec.user = request.user
437
        activation_key = hashlib.sha1(str(random()) + smart_str(ec.new_email_address))
438
        ec.activation_key=activation_key.hexdigest()
439
        if commit:
440
            ec.save()
441
        send_change_email(ec, request, email_template_name=email_template_name)
442

    
443
class SignApprovalTermsForm(forms.ModelForm):
444
    class Meta:
445
        model = AstakosUser
446
        fields = ("has_signed_terms",)
447

    
448
    def __init__(self, *args, **kwargs):
449
        super(SignApprovalTermsForm, self).__init__(*args, **kwargs)
450

    
451
    def clean_has_signed_terms(self):
452
        has_signed_terms = self.cleaned_data['has_signed_terms']
453
        if not has_signed_terms:
454
            raise forms.ValidationError(_('You have to agree with the terms'))
455
        return has_signed_terms
456

    
457
class InvitationForm(forms.ModelForm):
458
    username = forms.EmailField(label=_("Email"))
459
    
460
    def __init__(self, *args, **kwargs):
461
        super(InvitationForm, self).__init__(*args, **kwargs)
462
    
463
    class Meta:
464
        model = Invitation
465
        fields = ('username', 'realname')
466
    
467
    def clean_username(self):
468
        username = self.cleaned_data['username']
469
        try:
470
            Invitation.objects.get(username = username)
471
            raise forms.ValidationError(_('There is already invitation for this email.'))
472
        except Invitation.DoesNotExist:
473
            pass
474
        return username
475

    
476
class ExtendedPasswordChangeForm(PasswordChangeForm):
477
    """
478
    Extends PasswordChangeForm by enabling user
479
    to optionally renew also the token.
480
    """
481
    renew = forms.BooleanField(label='Renew token', required=False)
482
    
483
    def __init__(self, user, *args, **kwargs):
484
        super(ExtendedPasswordChangeForm, self).__init__(user, *args, **kwargs)
485
    
486
    def save(self, commit=True):
487
        user = super(ExtendedPasswordChangeForm, self).save(commit=False)
488
        if self.cleaned_data.get('renew'):
489
            user.renew_token()
490
        if commit:
491
            user.save()
492
        return user
493

    
494
class AstakosGroupCreationForm(forms.ModelForm):
495
#     issue_date = forms.DateField(widget=SelectDateWidget())
496
#     expiration_date = forms.DateField(widget=SelectDateWidget())
497
    kind = forms.ModelChoiceField(
498
        queryset=GroupKind.objects.all(),
499
        label="",
500
        widget=forms.HiddenInput()
501
    )
502
    name = forms.URLField()
503
    homepage = forms.URLField()
504
    moderation_enabled = forms.BooleanField(
505
        help_text="Check if you want to approve members participation manually",
506
        required=False   
507
    )
508
    
509
    class Meta:
510
        model = AstakosGroup
511
    
512
    def __init__(self, *args, **kwargs):
513
        try:
514
            resources = kwargs.pop('resources')
515
        except KeyError:
516
            resources = {}
517
        super(AstakosGroupCreationForm, self).__init__(*args, **kwargs)
518
        self.fields.keyOrder = ['kind', 'name', 'homepage', 'desc', 'issue_date',
519
                                'expiration_date', 'estimated_participants',
520
                                'moderation_enabled']
521
        for id, r in resources.iteritems():
522
            self.fields['resource_%s' % id] = forms.IntegerField(
523
                label=r,
524
                required=False,
525
                help_text=_('Leave it blank for no additional quota.')
526
            )
527
        
528
    def resources(self):
529
        for name, value in self.cleaned_data.items():
530
            prefix, delimiter, suffix = name.partition('resource_')
531
            if suffix:
532
                # yield only those having a value
533
                if not value:
534
                    continue
535
                yield (suffix, value)
536

    
537
class AstakosGroupSearchForm(forms.Form):
538
    q = forms.CharField(max_length=200, label='Search group')