Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / forms.py @ bf0c6de5

History | View | Annotate | Download (21.6 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, \
39
    PasswordResetForm, PasswordChangeForm, SetPasswordForm
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.models import fields_for_model
50

    
51
from astakos.im.models import (
52
    AstakosUser, Invitation, get_latest_terms,
53
    EmailChange, PendingThirdPartyUser
54
)
55
from astakos.im.settings import (INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL,
56
    BASEURL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL,
57
    RECAPTCHA_ENABLED, LOGGING_LEVEL, PASSWORD_RESET_EMAIL_SUBJECT,
58
    NEWPASSWD_INVALIDATE_TOKEN
59
)
60
from astakos.im.widgets import DummyWidget, RecaptchaWidget
61
from astakos.im.functions import send_change_email
62

    
63
# since Django 1.4 use django.core.urlresolvers.reverse_lazy instead
64
from astakos.im.util import reverse_lazy, reserved_email, get_query
65

    
66
import logging
67
import hashlib
68
import recaptcha.client.captcha as captcha
69
from random import random
70

    
71
logger = logging.getLogger(__name__)
72

    
73
class LocalUserCreationForm(UserCreationForm):
74
    """
75
    Extends the built in UserCreationForm in several ways:
76

77
    * Adds email, first_name, last_name, recaptcha_challenge_field, recaptcha_response_field field.
78
    * The username field isn't visible and it is assigned a generated id.
79
    * User created is not active.
80
    """
81
    recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
82
    recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
83

    
84
    class Meta:
85
        model = AstakosUser
86
        fields = ("email", "first_name", "last_name", "has_signed_terms", "has_signed_terms")
87

    
88
    def __init__(self, *args, **kwargs):
89
        """
90
        Changes the order of fields, and removes the username field.
91
        """
92
        request = kwargs.pop('request', None)
93
        if request:
94
            self.ip = request.META.get('REMOTE_ADDR',
95
                                       request.META.get('HTTP_X_REAL_IP', None))
96

    
97
        super(LocalUserCreationForm, self).__init__(*args, **kwargs)
98
        self.fields.keyOrder = ['email', 'first_name', 'last_name',
99
                                'password1', 'password2']
100

    
101
        if RECAPTCHA_ENABLED:
102
            self.fields.keyOrder.extend(['recaptcha_challenge_field',
103
                                         'recaptcha_response_field',])
104
        if get_latest_terms():
105
            self.fields.keyOrder.append('has_signed_terms')
106

    
107
        if 'has_signed_terms' in self.fields:
108
            # Overriding field label since we need to apply a link
109
            # to the terms within the label
110
            terms_link_html = '<a href="%s" target="_blank">%s</a>' \
111
                    % (reverse('latest_terms'), _("the terms"))
112
            self.fields['has_signed_terms'].label = \
113
                    mark_safe("I agree with %s" % terms_link_html)
114

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

    
123
    def clean_has_signed_terms(self):
124
        has_signed_terms = self.cleaned_data['has_signed_terms']
125
        if not has_signed_terms:
126
            raise forms.ValidationError(_('You have to agree with the terms'))
127
        return has_signed_terms
128

    
129
    def clean_recaptcha_response_field(self):
130
        if 'recaptcha_challenge_field' in self.cleaned_data:
131
            self.validate_captcha()
132
        return self.cleaned_data['recaptcha_response_field']
133

    
134
    def clean_recaptcha_challenge_field(self):
135
        if 'recaptcha_response_field' in self.cleaned_data:
136
            self.validate_captcha()
137
        return self.cleaned_data['recaptcha_challenge_field']
138

    
139
    def validate_captcha(self):
140
        rcf = self.cleaned_data['recaptcha_challenge_field']
141
        rrf = self.cleaned_data['recaptcha_response_field']
142
        check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
143
        if not check.is_valid:
144
            raise forms.ValidationError(_('You have not entered the correct words'))
145

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

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

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

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

    
176

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

    
187
class ThirdPartyUserCreationForm(forms.ModelForm):
188
    id = forms.CharField(
189
        widget=forms.HiddenInput(),
190
        label='',
191
        required=False
192
    )
193
    third_party_identifier = forms.CharField(
194
        widget=forms.HiddenInput(),
195
        label=''
196
    )
197
    class Meta:
198
        model = AstakosUser
199
        fields = ['id', 'email', 'third_party_identifier', 'first_name', 'last_name']
200

    
201
    def __init__(self, *args, **kwargs):
202
        """
203
        Changes the order of fields, and removes the username field.
204
        """
205
        self.request = kwargs.get('request', None)
206
        if self.request:
207
            kwargs.pop('request')
208
                
209
        latest_terms = get_latest_terms()
210
        if latest_terms:
211
            self._meta.fields.append('has_signed_terms')
212
        
213
        super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
214
        
215
        if latest_terms:
216
            self.fields.keyOrder.append('has_signed_terms')
217
        
218
        if 'has_signed_terms' in self.fields:
219
            # Overriding field label since we need to apply a link
220
            # to the terms within the label
221
            terms_link_html = '<a href="%s" target="_blank">%s</a>' \
222
                    % (reverse('latest_terms'), _("the terms"))
223
            self.fields['has_signed_terms'].label = \
224
                    mark_safe("I agree with %s" % terms_link_html)
225
    
226
    def clean_email(self):
227
        email = self.cleaned_data['email']
228
        if not email:
229
            raise forms.ValidationError(_("This field is required"))
230
        return email
231

    
232
    def clean_has_signed_terms(self):
233
        has_signed_terms = self.cleaned_data['has_signed_terms']
234
        if not has_signed_terms:
235
            raise forms.ValidationError(_('You have to agree with the terms'))
236
        return has_signed_terms
237

    
238
    def save(self, commit=True):
239
        user = super(ThirdPartyUserCreationForm, self).save(commit=False)
240
        user.set_unusable_password()
241
        user.provider = get_query(self.request).get('provider')
242
        if commit:
243
            user.save()
244
            logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, [])
245
        return user
246

    
247
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
248
    """
249
    Extends the ThirdPartyUserCreationForm: email is readonly.
250
    """
251
    def __init__(self, *args, **kwargs):
252
        """
253
        Changes the order of fields, and removes the username field.
254
        """
255
        super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
256

    
257
        #set readonly form fields
258
        ro = ('email',)
259
        for f in ro:
260
            self.fields[f].widget.attrs['readonly'] = True
261

    
262
    def save(self, commit=True):
263
        user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False)
264
        level = user.invitation.inviter.level + 1
265
        user.level = level
266
        user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
267
        user.email_verified = True
268
        if commit:
269
            user.save()
270
        return user
271

    
272
class ShibbolethUserCreationForm(ThirdPartyUserCreationForm):
273
    additional_email = forms.CharField(widget=forms.HiddenInput(), label='', required = False)
274

    
275
    def __init__(self, *args, **kwargs):
276
        super(ShibbolethUserCreationForm, self).__init__(*args, **kwargs)
277
        # copy email value to additional_mail in case user will change it
278
        name = 'email'
279
        field = self.fields[name]
280
        self.initial['additional_email'] = self.initial.get(name, field.initial)
281
        self.initial['email'] = None
282
    
283
    def clean_email(self):
284
        email = self.cleaned_data['email']
285
        if self.instance:
286
            if self.instance.email == email:
287
                raise forms.ValidationError(_("This is your current email."))
288
        for user in AstakosUser.objects.filter(email=email):
289
            if user.provider == 'shibboleth':
290
                raise forms.ValidationError(_(
291
                        "This email is already associated with another \
292
                         shibboleth account."
293
                    )
294
                )
295
            else:
296
                raise forms.ValidationError(_("This email is already used"))
297
        super(ShibbolethUserCreationForm, self).clean_email()
298
        return email
299
    
300
    def save(self, commit=True):
301
        user = super(ShibbolethUserCreationForm, self).save(commit=False)
302
        try:
303
            p = PendingThirdPartyUser.objects.get(
304
                provider=user.provider,
305
                third_party_identifier=user.third_party_identifier
306
            )
307
        except:
308
            pass
309
        else:
310
            p.delete()
311
        return user
312

    
313
class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, InvitedThirdPartyUserCreationForm):
314
    pass
315

    
316
class LoginForm(AuthenticationForm):
317
    username = forms.EmailField(label=_("Email"))
318
    recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
319
    recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
320

    
321
    def __init__(self, *args, **kwargs):
322
        was_limited = kwargs.get('was_limited', False)
323
        request = kwargs.get('request', None)
324
        if request:
325
            self.ip = request.META.get('REMOTE_ADDR',
326
                                       request.META.get('HTTP_X_REAL_IP', None))
327

    
328
        t = ('request', 'was_limited')
329
        for elem in t:
330
            if elem in kwargs.keys():
331
                kwargs.pop(elem)
332
        super(LoginForm, self).__init__(*args, **kwargs)
333

    
334
        self.fields.keyOrder = ['username', 'password']
335
        if was_limited and RECAPTCHA_ENABLED:
336
            self.fields.keyOrder.extend(['recaptcha_challenge_field',
337
                                         'recaptcha_response_field',])
338

    
339
    def clean_recaptcha_response_field(self):
340
        if 'recaptcha_challenge_field' in self.cleaned_data:
341
            self.validate_captcha()
342
        return self.cleaned_data['recaptcha_response_field']
343

    
344
    def clean_recaptcha_challenge_field(self):
345
        if 'recaptcha_response_field' in self.cleaned_data:
346
            self.validate_captcha()
347
        return self.cleaned_data['recaptcha_challenge_field']
348

    
349
    def validate_captcha(self):
350
        rcf = self.cleaned_data['recaptcha_challenge_field']
351
        rrf = self.cleaned_data['recaptcha_response_field']
352
        check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
353
        if not check.is_valid:
354
            raise forms.ValidationError(_('You have not entered the correct words'))
355
    
356
    def clean(self):
357
        """
358
        Override default behavior in order to check user's activation later
359
        """
360
        try:
361
            super(LoginForm, self).clean()
362
        except forms.ValidationError, e:
363
            if self.user_cache is None:
364
                raise
365
            if self.request:
366
                if not self.request.session.test_cookie_worked():
367
                    raise
368
        return self.cleaned_data
369

    
370
class ProfileForm(forms.ModelForm):
371
    """
372
    Subclass of ``ModelForm`` for permiting user to edit his/her profile.
373
    Most of the fields are readonly since the user is not allowed to change them.
374

375
    The class defines a save method which sets ``is_verified`` to True so as the user
376
    during the next login will not to be redirected to profile page.
377
    """
378
    renew = forms.BooleanField(label='Renew token', required=False)
379

    
380
    class Meta:
381
        model = AstakosUser
382
        fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires')
383

    
384
    def __init__(self, *args, **kwargs):
385
        self.session_key = kwargs.pop('session_key', None)
386
        super(ProfileForm, self).__init__(*args, **kwargs)
387
        instance = getattr(self, 'instance', None)
388
        ro_fields = ('email', 'auth_token', 'auth_token_expires')
389
        if instance and instance.id:
390
            for field in ro_fields:
391
                self.fields[field].widget.attrs['readonly'] = True
392

    
393
    def save(self, commit=True):
394
        user = super(ProfileForm, self).save(commit=False)
395
        user.is_verified = True
396
        if self.cleaned_data.get('renew'):
397
            user.renew_token(
398
                flush_sessions=True,
399
                current_key=self.session_key
400
            )
401
        if commit:
402
            user.save()
403
        return user
404

    
405
class FeedbackForm(forms.Form):
406
    """
407
    Form for writing feedback.
408
    """
409
    feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
410
    feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
411
                                    required=False)
412

    
413
class SendInvitationForm(forms.Form):
414
    """
415
    Form for sending an invitations
416
    """
417

    
418
    email = forms.EmailField(required = True, label = 'Email address')
419
    first_name = forms.EmailField(label = 'First name')
420
    last_name = forms.EmailField(label = 'Last name')
421

    
422
class ExtendedPasswordResetForm(PasswordResetForm):
423
    """
424
    Extends PasswordResetForm by overriding save method:
425
    passes a custom from_email in send_mail.
426

427
    Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
428
    accepts a from_email argument.
429
    """
430
    def clean_email(self):
431
        email = super(ExtendedPasswordResetForm, self).clean_email()
432
        try:
433
            user = AstakosUser.objects.get(email=email, is_active=True)
434
            if not user.has_usable_password():
435
                raise forms.ValidationError(_("This account has not a usable password."))
436
        except AstakosUser.DoesNotExist, e:
437
            raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?'))
438
        return email
439

    
440
    def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
441
             use_https=False, token_generator=default_token_generator, request=None):
442
        """
443
        Generates a one-use only link for resetting password and sends to the user.
444
        """
445
        for user in self.users_cache:
446
            url = reverse('django.contrib.auth.views.password_reset_confirm',
447
                          kwargs={'uidb36':int_to_base36(user.id),
448
                                  'token':token_generator.make_token(user)})
449
            url = urljoin(BASEURL, url)
450
            t = loader.get_template(email_template_name)
451
            c = {
452
                'email': user.email,
453
                'url': url,
454
                'site_name': SITENAME,
455
                'user': user,
456
                'baseurl': BASEURL,
457
                'support': DEFAULT_CONTACT_EMAIL
458
            }
459
            from_email = DEFAULT_FROM_EMAIL
460
            send_mail(_(PASSWORD_RESET_EMAIL_SUBJECT),
461
                t.render(Context(c)), from_email, [user.email])
462

    
463
class EmailChangeForm(forms.ModelForm):
464
    class Meta:
465
        model = EmailChange
466
        fields = ('new_email_address',)
467

    
468
    def clean_new_email_address(self):
469
        addr = self.cleaned_data['new_email_address']
470
        if AstakosUser.objects.filter(email__iexact=addr):
471
            raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
472
        return addr
473

    
474
    def save(self, email_template_name, request, commit=True):
475
        ec = super(EmailChangeForm, self).save(commit=False)
476
        ec.user = request.user
477
        activation_key = hashlib.sha1(str(random()) + smart_str(ec.new_email_address))
478
        ec.activation_key=activation_key.hexdigest()
479
        if commit:
480
            ec.save()
481
        send_change_email(ec, request, email_template_name=email_template_name)
482

    
483
class SignApprovalTermsForm(forms.ModelForm):
484
    class Meta:
485
        model = AstakosUser
486
        fields = ("has_signed_terms",)
487

    
488
    def __init__(self, *args, **kwargs):
489
        super(SignApprovalTermsForm, self).__init__(*args, **kwargs)
490

    
491
    def clean_has_signed_terms(self):
492
        has_signed_terms = self.cleaned_data['has_signed_terms']
493
        if not has_signed_terms:
494
            raise forms.ValidationError(_('You have to agree with the terms'))
495
        return has_signed_terms
496

    
497
class InvitationForm(forms.ModelForm):
498
    username = forms.EmailField(label=_("Email"))
499

    
500
    def __init__(self, *args, **kwargs):
501
        super(InvitationForm, self).__init__(*args, **kwargs)
502

    
503
    class Meta:
504
        model = Invitation
505
        fields = ('username', 'realname')
506

    
507
    def clean_username(self):
508
        username = self.cleaned_data['username']
509
        try:
510
            Invitation.objects.get(username = username)
511
            raise forms.ValidationError(_('There is already invitation for this email.'))
512
        except Invitation.DoesNotExist:
513
            pass
514
        return username
515

    
516
class ExtendedPasswordChangeForm(PasswordChangeForm):
517
    """
518
    Extends PasswordChangeForm by enabling user
519
    to optionally renew also the token.
520
    """
521
    if not NEWPASSWD_INVALIDATE_TOKEN:
522
        renew = forms.BooleanField(label='Renew token', required=False,
523
                                   initial=True,
524
                                   help_text='Unsetting this may result in security risk.')
525

    
526
    def __init__(self, user, *args, **kwargs):
527
        self.session_key = kwargs.pop('session_key', None)
528
        super(ExtendedPasswordChangeForm, self).__init__(user, *args, **kwargs)
529

    
530
    def save(self, commit=True):
531
        try:
532
            if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'):
533
                self.user.renew_token()
534
            self.user.flush_sessions(current_key=self.session_key)
535
        except AttributeError:
536
            # if user model does has not such methods
537
            pass
538
        return super(ExtendedPasswordChangeForm, self).save(commit=commit)
539

    
540
class ExtendedSetPasswordForm(SetPasswordForm):
541
    """
542
    Extends SetPasswordForm by enabling user
543
    to optionally renew also the token.
544
    """
545
    if not NEWPASSWD_INVALIDATE_TOKEN:
546
        renew = forms.BooleanField(
547
            label='Renew token',
548
            required=False,
549
            initial=True,
550
            help_text='Unsetting this may result in security risk.'
551
        )
552
    
553
    def __init__(self, user, *args, **kwargs):
554
        super(ExtendedSetPasswordForm, self).__init__(user, *args, **kwargs)
555
    
556
    def save(self, commit=True):
557
        try:
558
            self.user = AstakosUser.objects.get(id=self.user.id)
559
            if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'):
560
                self.user.renew_token()
561
            self.user.flush_sessions()
562
        except BaseException, e:
563
            logger.exception(e)
564
            pass
565
        return super(ExtendedSetPasswordForm, self).save(commit=commit)