Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / forms.py @ 2c669a3a

History | View | Annotate | Download (17.3 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
from django.contrib import messages
47
from django.utils.encoding import smart_str
48
from captcha.fields import ReCaptchaField
49

    
50
from astakos.im.models import AstakosUser, Invitation, get_latest_terms, EmailChange
51
from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, \
52
    BASEURL, SITENAME, DEFAULT_CONTACT_EMAIL, \
53
    RECAPTCHA_ENABLED, RECAPTCHA_PRIVATE_KEY, RECAPTCHA_PUBLIC_KEY, RECAPTCHA_USE_SSL, RECAPTCHA_OPTIONS, \
54
    LOGGING_LEVEL
55
from astakos.im.widgets import DummyWidget, RecaptchaWidget
56
from astakos.im.functions import send_change_email
57

    
58
# since Django 1.4 use django.core.urlresolvers.reverse_lazy instead
59
from astakos.im.util import reverse_lazy, reserved_email, get_query
60

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

    
66
logger = logging.getLogger(__name__)
67

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

72
    * Adds email, first_name, last_name, recaptcha_challenge_field field.
73
    * The username field isn't visible and it is assigned a generated id.
74
    * User created is not active.
75
    """
76
    recaptcha_challenge_field = ReCaptchaField(private_key=RECAPTCHA_PRIVATE_KEY,
77
                                                public_key=RECAPTCHA_PUBLIC_KEY,
78
                                                use_ssl=RECAPTCHA_USE_SSL,
79
                                                attrs=RECAPTCHA_OPTIONS)
80

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

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

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

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

    
119
    def clean_has_signed_terms(self):
120
        has_signed_terms = self.cleaned_data['has_signed_terms']
121
        if not has_signed_terms:
122
            raise forms.ValidationError(_('You have to agree with the terms'))
123
        return has_signed_terms
124
    
125
    def save(self, commit=True):
126
        """
127
        Saves the email, first_name and last_name properties, after the normal
128
        save behavior is complete.
129
        """
130
        user = super(LocalUserCreationForm, self).save(commit=False)
131
        user.renew_token()
132
        if commit:
133
            user.save()
134
            logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, [])
135
        return user
136

    
137
class InvitedLocalUserCreationForm(LocalUserCreationForm):
138
    """
139
    Extends the LocalUserCreationForm: email is readonly.
140
    """
141
    class Meta:
142
        model = AstakosUser
143
        fields = ("email", "first_name", "last_name", "has_signed_terms")
144

    
145
    def __init__(self, *args, **kwargs):
146
        """
147
        Changes the order of fields, and removes the username field.
148
        """
149
        super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs)
150

    
151
        #set readonly form fields
152
        ro = ('email', 'username',)
153
        for f in ro:
154
            self.fields[f].widget.attrs['readonly'] = True
155
        
156

    
157
    def save(self, commit=True):
158
        user = super(InvitedLocalUserCreationForm, self).save(commit=False)
159
        level = user.invitation.inviter.level + 1
160
        user.level = level
161
        user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
162
        user.email_verified = True
163
        if commit:
164
            user.save()
165
        return user
166

    
167
class ThirdPartyUserCreationForm(forms.ModelForm):
168
    class Meta:
169
        model = AstakosUser
170
        fields = ("email", "first_name", "last_name", "third_party_identifier", "has_signed_terms")
171
    
172
    def __init__(self, *args, **kwargs):
173
        """
174
        Changes the order of fields, and removes the username field.
175
        """
176
        self.request = kwargs.get('request', None)
177
        if self.request:
178
            kwargs.pop('request')
179
        super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
180
        self.fields.keyOrder = ['email', 'first_name', 'last_name', 'third_party_identifier']
181
        if get_latest_terms():
182
            self.fields.keyOrder.append('has_signed_terms')
183
        #set readonly form fields
184
        ro = ["third_party_identifier"]
185
        for f in ro:
186
            self.fields[f].widget.attrs['readonly'] = True
187
        
188
        if 'has_signed_terms' in self.fields:
189
            # Overriding field label since we need to apply a link
190
            # to the terms within the label
191
            terms_link_html = '<a href="%s" target="_blank">%s</a>' \
192
                    % (reverse('latest_terms'), _("the terms"))
193
            self.fields['has_signed_terms'].label = \
194
                    mark_safe("I agree with %s" % terms_link_html)
195
    
196
    def clean_email(self):
197
        email = self.cleaned_data['email']
198
        if not email:
199
            raise forms.ValidationError(_("This field is required"))
200
        return email
201
    
202
    def clean_has_signed_terms(self):
203
        has_signed_terms = self.cleaned_data['has_signed_terms']
204
        if not has_signed_terms:
205
            raise forms.ValidationError(_('You have to agree with the terms'))
206
        return has_signed_terms
207
    
208
    def save(self, commit=True):
209
        user = super(ThirdPartyUserCreationForm, self).save(commit=False)
210
        user.renew_token()
211
        user.provider = get_query(self.request).get('provider')
212
        if commit:
213
            user.save()
214
            logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, [])
215
        return user
216

    
217
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
218
    """
219
    Extends the ThirdPartyUserCreationForm: email is readonly.
220
    """
221
    def __init__(self, *args, **kwargs):
222
        """
223
        Changes the order of fields, and removes the username field.
224
        """
225
        super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
226

    
227
        #set readonly form fields
228
        ro = ('email',)
229
        for f in ro:
230
            self.fields[f].widget.attrs['readonly'] = True
231
    
232
    def save(self, commit=True):
233
        user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False)
234
        level = user.invitation.inviter.level + 1
235
        user.level = level
236
        user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
237
        user.email_verified = True
238
        if commit:
239
            user.save()
240
        return user
241

    
242
class ShibbolethUserCreationForm(ThirdPartyUserCreationForm):
243
    additional_email = forms.CharField(widget=forms.HiddenInput(), label='', required = False)
244
    
245
    def __init__(self, *args, **kwargs):
246
        super(ShibbolethUserCreationForm, self).__init__(*args, **kwargs)
247
        self.fields.keyOrder.append('additional_email')
248
        # copy email value to additional_mail in case user will change it
249
        name = 'email'
250
        field = self.fields[name]
251
        self.initial['additional_email'] = self.initial.get(name, field.initial)
252
    
253
    def clean_email(self):
254
        email = self.cleaned_data['email']
255
        for user in AstakosUser.objects.filter(email = email):
256
            if user.provider == 'shibboleth':
257
                raise forms.ValidationError(_("This email is already associated with another shibboleth account."))
258
            elif not user.is_active:
259
                raise forms.ValidationError(_("This email is already associated with an inactive account. \
260
                                              You need to wait to be activated before being able to switch to a shibboleth account."))
261
        super(ShibbolethUserCreationForm, self).clean_email()
262
        return email
263

    
264
class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, InvitedThirdPartyUserCreationForm):
265
    pass
266
    
267
class LoginForm(AuthenticationForm):
268
    username = forms.EmailField(label=_("Email"))
269
    recaptcha_challenge_field = ReCaptchaField(private_key=RECAPTCHA_PRIVATE_KEY,
270
                                                public_key=RECAPTCHA_PUBLIC_KEY,
271
                                                use_ssl=RECAPTCHA_USE_SSL,
272
                                                attrs=RECAPTCHA_OPTIONS)
273
    
274
    def __init__(self, *args, **kwargs):
275
        was_limited = kwargs.get('was_limited', False)
276
        request = kwargs.get('request', None)
277
        if request:
278
            self.ip = request.META.get('REMOTE_ADDR',
279
                                       request.META.get('HTTP_X_REAL_IP', None))
280
        
281
        t = ('request', 'was_limited')
282
        for elem in t:
283
            if elem in kwargs.keys():
284
                kwargs.pop(elem)
285
        super(LoginForm, self).__init__(*args, **kwargs)
286
        
287
        self.fields.keyOrder = ['username', 'password']
288
        if was_limited and RECAPTCHA_ENABLED:
289
            self.fields.keyOrder.extend(['recaptcha_challenge_field'])
290

    
291
class ProfileForm(forms.ModelForm):
292
    """
293
    Subclass of ``ModelForm`` for permiting user to edit his/her profile.
294
    Most of the fields are readonly since the user is not allowed to change them.
295

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

    
301
    class Meta:
302
        model = AstakosUser
303
        fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires')
304

    
305
    def __init__(self, *args, **kwargs):
306
        super(ProfileForm, self).__init__(*args, **kwargs)
307
        instance = getattr(self, 'instance', None)
308
        ro_fields = ('email', 'auth_token', 'auth_token_expires')
309
        if instance and instance.id:
310
            for field in ro_fields:
311
                self.fields[field].widget.attrs['readonly'] = True
312

    
313
    def save(self, commit=True):
314
        user = super(ProfileForm, self).save(commit=False)
315
        user.is_verified = True
316
        if self.cleaned_data.get('renew'):
317
            user.renew_token()
318
        if commit:
319
            user.save()
320
        return user
321

    
322
class FeedbackForm(forms.Form):
323
    """
324
    Form for writing feedback.
325
    """
326
    feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
327
    feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
328
                                    required=False)
329

    
330
class SendInvitationForm(forms.Form):
331
    """
332
    Form for sending an invitations
333
    """
334

    
335
    email = forms.EmailField(required = True, label = 'Email address')
336
    first_name = forms.EmailField(label = 'First name')
337
    last_name = forms.EmailField(label = 'Last name')
338

    
339
class ExtendedPasswordResetForm(PasswordResetForm):
340
    """
341
    Extends PasswordResetForm by overriding save method:
342
    passes a custom from_email in send_mail.
343

344
    Since Django 1.3 this is obsolete since ``django.contrib.auth.views.reset_password``
345
    accepts a from_email argument.
346
    """
347
    def clean_email(self):
348
        email = super(ExtendedPasswordResetForm, self).clean_email()
349
        try:
350
            user = AstakosUser.objects.get(email=email, is_active=True)
351
            if not user.has_usable_password():
352
                raise forms.ValidationError(_("This account does not have a usable password."))
353
        except AstakosUser.DoesNotExist, e:
354
            raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?'))
355
        return email
356
    
357
    def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
358
             use_https=False, token_generator=default_token_generator, request=None):
359
        """
360
        Generates a one-use only link for resetting password and sends to the user.
361
        """
362
        for user in self.users_cache:
363
            url = reverse('django.contrib.auth.views.password_reset_confirm',
364
                          kwargs={'uidb36':int_to_base36(user.id),
365
                                  'token':token_generator.make_token(user)})
366
            url = urljoin(BASEURL, url)
367
            t = loader.get_template(email_template_name)
368
            c = {
369
                'email': user.email,
370
                'url': url,
371
                'site_name': SITENAME,
372
                'user': user,
373
                'baseurl': BASEURL,
374
                'support': DEFAULT_CONTACT_EMAIL
375
            }
376
            from_email = DEFAULT_FROM_EMAIL
377
            send_mail(_("Password reset on %s alpha2 testing") % SITENAME,
378
                t.render(Context(c)), from_email, [user.email])
379

    
380
class EmailChangeForm(forms.ModelForm):
381
    class Meta:
382
        model = EmailChange
383
        fields = ('new_email_address',)
384
            
385
    def clean_new_email_address(self):
386
        addr = self.cleaned_data['new_email_address']
387
        if AstakosUser.objects.filter(email__iexact=addr):
388
            raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
389
        return addr
390
    
391
    def save(self, email_template_name, request, commit=True):
392
        ec = super(EmailChangeForm, self).save(commit=False)
393
        ec.user = request.user
394
        activation_key = hashlib.sha1(str(random()) + smart_str(ec.new_email_address))
395
        ec.activation_key=activation_key.hexdigest()
396
        if commit:
397
            ec.save()
398
        send_change_email(ec, request, email_template_name=email_template_name)
399

    
400
class SignApprovalTermsForm(forms.ModelForm):
401
    class Meta:
402
        model = AstakosUser
403
        fields = ("has_signed_terms",)
404

    
405
    def __init__(self, *args, **kwargs):
406
        super(SignApprovalTermsForm, self).__init__(*args, **kwargs)
407

    
408
    def clean_has_signed_terms(self):
409
        has_signed_terms = self.cleaned_data['has_signed_terms']
410
        if not has_signed_terms:
411
            raise forms.ValidationError(_('You have to agree with the terms'))
412
        return has_signed_terms
413

    
414
class InvitationForm(forms.ModelForm):
415
    username = forms.EmailField(label=_("Email"))
416
    
417
    def __init__(self, *args, **kwargs):
418
        super(InvitationForm, self).__init__(*args, **kwargs)
419
    
420
    class Meta:
421
        model = Invitation
422
        fields = ('username', 'realname')
423
    
424
    def clean_username(self):
425
        username = self.cleaned_data['username']
426
        try:
427
            Invitation.objects.get(username = username)
428
            raise forms.ValidationError(_('There is already invitation for this email.'))
429
        except Invitation.DoesNotExist:
430
            pass
431
        return username