Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / forms.py @ 63fa03fe

History | View | Annotate | Download (17.8 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, 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

    
47
from astakos.im.models import AstakosUser, Invitation
48
from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL, RECAPTCHA_ENABLED
49
from astakos.im.widgets import DummyWidget, RecaptchaWidget, ApprovalTermsWidget
50

    
51
# since Django 1.4 use django.core.urlresolvers.reverse_lazy instead
52
from astakos.im.util import reverse_lazy, get_latest_terms
53

    
54
import logging
55
import recaptcha.client.captcha as captcha
56

    
57
logger = logging.getLogger(__name__)
58

    
59
class LocalUserCreationForm(UserCreationForm):
60
    """
61
    Extends the built in UserCreationForm in several ways:
62

63
    * Adds email, first_name, last_name, recaptcha_challenge_field, recaptcha_response_field field.
64
    * The username field isn't visible and it is assigned a generated id.
65
    * User created is not active.
66
    """
67
    recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
68
    recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='')
69

    
70
    class Meta:
71
        model = AstakosUser
72
        fields = ("email", "first_name", "last_name", "has_signed_terms")
73
        widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))}
74

    
75
    def __init__(self, *args, **kwargs):
76
        """
77
        Changes the order of fields, and removes the username field.
78
        """
79
        request = kwargs.get('request', None)
80
        if request:
81
            kwargs.pop('request')
82
            self.ip = request.META.get('REMOTE_ADDR',
83
                                       request.META.get('HTTP_X_REAL_IP', None))
84
        
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')
90
        if RECAPTCHA_ENABLED:
91
            self.fields.keyOrder.extend(['recaptcha_challenge_field',
92
                                         'recaptcha_response_field',])
93

    
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)
101

    
102
    def clean_email(self):
103
        email = self.cleaned_data['email']
104
        if not email:
105
            raise forms.ValidationError(_("This field is required"))
106
        try:
107
            AstakosUser.objects.get(email = email)
108
            raise forms.ValidationError(_("This email is already used"))
109
        except AstakosUser.DoesNotExist:
110
            return email
111

    
112
    def clean_has_signed_terms(self):
113
        has_signed_terms = self.cleaned_data['has_signed_terms']
114
        if not has_signed_terms:
115
            raise forms.ValidationError(_('You have to agree with the terms'))
116
        return has_signed_terms
117

    
118
    def clean_recaptcha_response_field(self):
119
        if 'recaptcha_challenge_field' in self.cleaned_data:
120
            self.validate_captcha()
121
        return self.cleaned_data['recaptcha_response_field']
122

    
123
    def clean_recaptcha_challenge_field(self):
124
        if 'recaptcha_response_field' in self.cleaned_data:
125
            self.validate_captcha()
126
        return self.cleaned_data['recaptcha_challenge_field']
127

    
128
    def validate_captcha(self):
129
        rcf = self.cleaned_data['recaptcha_challenge_field']
130
        rrf = self.cleaned_data['recaptcha_response_field']
131
        check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
132
        if not check.is_valid:
133
            raise forms.ValidationError(_('You have not entered the correct words'))
134

    
135
    def save(self, commit=True):
136
        """
137
        Saves the email, first_name and last_name properties, after the normal
138
        save behavior is complete.
139
        """
140
        user = super(LocalUserCreationForm, self).save(commit=False)
141
        user.renew_token()
142
        if commit:
143
            user.save()
144
        logger.info('Created user %s', user)
145
        return user
146

    
147
class InvitedLocalUserCreationForm(LocalUserCreationForm):
148
    """
149
    Extends the LocalUserCreationForm: adds an inviter readonly field.
150
    """
151

    
152
    inviter = forms.CharField(widget=forms.TextInput(), label=_('Inviter Real Name'))
153

    
154
    class Meta:
155
        model = AstakosUser
156
        fields = ("email", "first_name", "last_name", "has_signed_terms")
157
        widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))}
158

    
159
    def __init__(self, *args, **kwargs):
160
        """
161
        Changes the order of fields, and removes the username field.
162
        """
163
        super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs)
164

    
165
        #set readonly form fields
166
        ro = ('inviter', 'email', 'username',)
167
        for f in ro:
168
            self.fields[f].widget.attrs['readonly'] = True
169
        
170

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

    
181
class ThirdPartyUserCreationForm(forms.ModelForm):
182
    class Meta:
183
        model = AstakosUser
184
        fields = ("email", "first_name", "last_name", "third_party_identifier",
185
                  "has_signed_terms", "provider")
186
        widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))}
187
    
188
    def __init__(self, *args, **kwargs):
189
        """
190
        Changes the order of fields, and removes the username field.
191
        """
192
        super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
193
        self.fields.keyOrder = ['email', 'first_name', 'last_name',
194
                                'provider', 'third_party_identifier']
195
        if get_latest_terms():
196
            self.fields.keyOrder.append('has_signed_terms')
197
        #set readonly form fields
198
        ro = ["provider", "third_party_identifier", "first_name", "last_name"]
199
        for f in ro:
200
            self.fields[f].widget.attrs['readonly'] = True
201
        
202
        if 'has_signed_terms' in self.fields:
203
            # Overriding field label since we need to apply a link
204
            # to the terms within the label
205
            terms_link_html = '<a href="%s" target="_blank">%s</a>' \
206
                    % (reverse('latest_terms'), _("the terms"))
207
            self.fields['has_signed_terms'].label = \
208
                    mark_safe("I agree with %s" % terms_link_html)
209
    
210
    def clean_email(self):
211
        email = self.cleaned_data['email']
212
        if not email:
213
            raise forms.ValidationError(_("This field is required"))
214
        try:
215
            AstakosUser.objects.get(email = email)
216
            raise forms.ValidationError(_("This email is already used"))
217
        except AstakosUser.DoesNotExist:
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
        if commit:
231
            user.save()
232
        logger.info('Created user %s', user)
233
        return user
234

    
235
#class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
236
#    def __init__(self, *args, **kwargs):
237
#        super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
238
#        #set readonly form fields
239
#        self.fields['email'].widget.attrs['readonly'] = True
240

    
241
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
242
    """
243
    Extends the LocalUserCreationForm: adds an inviter readonly field.
244
    """
245
    inviter = forms.CharField(widget=forms.TextInput(), label=_('Inviter Real Name'))
246
    
247
    def __init__(self, *args, **kwargs):
248
        """
249
        Changes the order of fields, and removes the username field.
250
        """
251
        super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
252

    
253
        #set readonly form fields
254
        ro = ('inviter', 'email',)
255
        for f in ro:
256
            self.fields[f].widget.attrs['readonly'] = True
257
    
258
    def save(self, commit=True):
259
        user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False)
260
        level = user.invitation.inviter.level + 1
261
        user.level = level
262
        user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
263
        user.email_verified = True
264
        if commit:
265
            user.save()
266
        return user
267

    
268
class ShibbolethUserCreationForm(ThirdPartyUserCreationForm):
269
    def clean_email(self):
270
        email = self.cleaned_data['email']
271
        if not email:
272
            raise forms.ValidationError(_("This field is required"))
273
        try:
274
            user = AstakosUser.objects.get(email = email)
275
            if user.provider == 'local':
276
                self.instance = user
277
                return email
278
            else:
279
                raise forms.ValidationError(_("This email is already associated with another shibboleth account."))
280
        except AstakosUser.DoesNotExist:
281
            return email
282

    
283
class InvitedShibbolethUserCreationForm(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
class ProfileForm(forms.ModelForm):
327
    """
328
    Subclass of ``ModelForm`` for permiting user to edit his/her profile.
329
    Most of the fields are readonly since the user is not allowed to change them.
330

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

    
336
    class Meta:
337
        model = AstakosUser
338
        fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires', 'groups')
339

    
340
    def __init__(self, *args, **kwargs):
341
        super(ProfileForm, self).__init__(*args, **kwargs)
342
        instance = getattr(self, 'instance', None)
343
        ro_fields = ('auth_token', 'auth_token_expires', 'groups')
344
        if instance and instance.id:
345
            for field in ro_fields:
346
                self.fields[field].widget.attrs['readonly'] = True
347

    
348
    def save(self, commit=True):
349
        user = super(ProfileForm, self).save(commit=False)
350
        user.is_verified = True
351
        if self.cleaned_data.get('renew'):
352
            user.renew_token()
353
        if commit:
354
            user.save()
355
        return user
356

    
357
class FeedbackForm(forms.Form):
358
    """
359
    Form for writing feedback.
360
    """
361
    feedback_msg = forms.CharField(widget=forms.TextInput(), label=u'Message')
362
    feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
363
                                    required=False)
364

    
365
class SendInvitationForm(forms.Form):
366
    """
367
    Form for sending an invitations
368
    """
369

    
370
    email = forms.EmailField(required = True, label = 'Email address')
371
    first_name = forms.EmailField(label = 'First name')
372
    last_name = forms.EmailField(label = 'Last name')
373

    
374
class ExtendedPasswordResetForm(PasswordResetForm):
375
    """
376
    Extends PasswordResetForm by overriding save method:
377
    passes a custom from_email in send_mail.
378

379
    Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
380
    accepts a from_email argument.
381
    """
382
    def clean_email(self):
383
        email = super(ExtendedPasswordResetForm, self).clean_email()
384
        try:
385
            user = AstakosUser.objects.get(email=email)
386
            if not user.has_usable_password():
387
                raise forms.ValidationError(_("This account has not a usable password."))
388
        except AstakosUser.DoesNotExist, e:
389
            raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?'))
390
        return email
391
    
392
    def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
393
             use_https=False, token_generator=default_token_generator, request=None):
394
        """
395
        Generates a one-use only link for resetting password and sends to the user.
396
        """
397
        for user in self.users_cache:
398
            url = reverse('django.contrib.auth.views.password_reset_confirm',
399
                          kwargs={'uidb36':int_to_base36(user.id),
400
                                  'token':token_generator.make_token(user)})
401
            url = request.build_absolute_uri(url)
402
            t = loader.get_template(email_template_name)
403
            c = {
404
                'email': user.email,
405
                'url': url,
406
                'site_name': SITENAME,
407
                'user': user,
408
                'baseurl': request.build_absolute_uri(),
409
                'support': DEFAULT_CONTACT_EMAIL
410
            }
411
            from_email = DEFAULT_FROM_EMAIL
412
            send_mail(_("Password reset on %s alpha2 testing") % SITENAME,
413
                t.render(Context(c)), from_email, [user.email])
414

    
415
class SignApprovalTermsForm(forms.ModelForm):
416
    class Meta:
417
        model = AstakosUser
418
        fields = ("has_signed_terms",)
419

    
420
    def __init__(self, *args, **kwargs):
421
        super(SignApprovalTermsForm, self).__init__(*args, **kwargs)
422

    
423
    def clean_has_signed_terms(self):
424
        has_signed_terms = self.cleaned_data['has_signed_terms']
425
        if not has_signed_terms:
426
            raise forms.ValidationError(_('You have to agree with the terms'))
427
        return has_signed_terms
428

    
429
class InvitationForm(forms.ModelForm):
430
    username = forms.EmailField(label=_("Email"))
431
    
432
    def __init__(self, *args, **kwargs):
433
        super(InvitationForm, self).__init__(*args, **kwargs)
434
    
435
    class Meta:
436
        model = Invitation
437
        fields = ('username', 'realname')
438
    
439
    def clean_username(self):
440
        username = self.cleaned_data['username']
441
        try:
442
            Invitation.objects.get(username = username)
443
            raise forms.ValidationError(_('There is already invitation for this email.'))
444
        except Invitation.DoesNotExist:
445
            pass
446
        return username