Statistics
| Branch: | Tag: | Revision:

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

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

    
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
                                       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.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,
51
                               Invitation, Membership, GroupKind, Resource,
52
                               get_latest_terms)
53
from astakos.im.settings import (INVITATIONS_PER_LEVEL, BASEURL, SITENAME,
54
                                 RECAPTCHA_PRIVATE_KEY, RECAPTCHA_ENABLED,
55
                                 DEFAULT_CONTACT_EMAIL, LOGGING_LEVEL,
56
                                 PASSWORD_RESET_EMAIL_SUBJECT, 
57
                                 NEWPASSWD_INVALIDATE_TOKEN)
58
from astakos.im.widgets import DummyWidget, RecaptchaWidget
59
from astakos.im.functions import send_change_email
60

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

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

    
68
logger = logging.getLogger(__name__)
69

    
70

    
71
class LocalUserCreationForm(UserCreationForm):
72
    """
73
    Extends the built in UserCreationForm in several ways:
74

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

    
83
    class Meta:
84
        model = AstakosUser
85
        fields = ("email", "first_name", "last_name",
86
                  "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.get('request', None)
93
        if request:
94
            kwargs.pop('request')
95
            self.ip = request.META.get('REMOTE_ADDR',
96
                                       request.META.get('HTTP_X_REAL_IP', None))
97

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

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

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

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

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

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

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

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

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

    
160

    
161
class InvitedLocalUserCreationForm(LocalUserCreationForm):
162
    """
163
    Extends the LocalUserCreationForm: email is readonly.
164
    """
165
    class Meta:
166
        model = AstakosUser
167
        fields = ("email", "first_name", "last_name", "has_signed_terms")
168

    
169
    def __init__(self, *args, **kwargs):
170
        """
171
        Changes the order of fields, and removes the username field.
172
        """
173
        super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs)
174

    
175
        #set readonly form fields
176
        ro = ('email', 'username',)
177
        for f in ro:
178
            self.fields[f].widget.attrs['readonly'] = True
179
    
180
    def save(self, commit=True):
181
        user = super(InvitedLocalUserCreationForm, self).save(commit=False)
182
        level = user.invitation.inviter.level + 1
183
        user.level = level
184
        user.invitations = INVITATIONS_PER_LEVEL.get(level, 0)
185
        user.email_verified = True
186
        if commit:
187
            user.save()
188
        return user
189

    
190

    
191
class ThirdPartyUserCreationForm(forms.ModelForm):
192
    class Meta:
193
        model = AstakosUser
194
        fields = ("email", "first_name", "last_name",
195
                  "third_party_identifier", "has_signed_terms")
196
    
197
    def __init__(self, *args, **kwargs):
198
        """
199
        Changes the order of fields, and removes the username field.
200
        """
201
        self.request = kwargs.get('request', None)
202
        if self.request:
203
            kwargs.pop('request')
204
        super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
205
        self.fields.keyOrder = ['email', 'first_name', 'last_name',
206
                                'third_party_identifier']
207
        if get_latest_terms():
208
            self.fields.keyOrder.append('has_signed_terms')
209
        #set readonly form fields
210
        ro = ["third_party_identifier"]
211
        for f in ro:
212
            self.fields[f].widget.attrs['readonly'] = True
213

    
214
        if 'has_signed_terms' in self.fields:
215
            # Overriding field label since we need to apply a link
216
            # to the terms within the label
217
            terms_link_html = '<a href="%s" target="_blank">%s</a>' \
218
                % (reverse('latest_terms'), _("the terms"))
219
            self.fields['has_signed_terms'].label = \
220
                mark_safe("I agree with %s" % terms_link_html)
221
    
222
    def clean_email(self):
223
        email = self.cleaned_data['email']
224
        if not email:
225
            raise forms.ValidationError(_("This field is required"))
226
        return email
227

    
228
    def clean_has_signed_terms(self):
229
        has_signed_terms = self.cleaned_data['has_signed_terms']
230
        if not has_signed_terms:
231
            raise forms.ValidationError(_('You have to agree with the terms'))
232
        return has_signed_terms
233

    
234
    def save(self, commit=True):
235
        user = super(ThirdPartyUserCreationForm, self).save(commit=False)
236
        user.set_unusable_password()
237
        user.renew_token()
238
        user.provider = get_query(self.request).get('provider')
239
        if commit:
240
            user.save()
241
            logger.log(LOGGING_LEVEL, 'Created user %s' % user.email)
242
        return user
243

    
244

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

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

    
261
    def save(self, commit=True):
262
        user = super(
263
            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

    
273
class ShibbolethUserCreationForm(ThirdPartyUserCreationForm):
274
    additional_email = forms.CharField(
275
        widget=forms.HiddenInput(), label='', required=False)
276
    
277
    def __init__(self, *args, **kwargs):
278
        super(ShibbolethUserCreationForm, self).__init__(*args, **kwargs)
279
        self.fields.keyOrder.append('additional_email')
280
        # copy email value to additional_mail in case user will change it
281
        name = 'email'
282
        field = self.fields[name]
283
        self.initial['additional_email'] = self.initial.get(name,
284
                                                            field.initial)
285
    
286
    def clean_email(self):
287
        email = self.cleaned_data['email']
288
        for user in AstakosUser.objects.filter(email=email):
289
            if user.provider == 'shibboleth':
290
                raise forms.ValidationError(_("This email is already associated with another shibboleth account."))
291
            elif not user.is_active:
292
                raise forms.ValidationError(_("This email is already associated with an inactive account. \
293
                                              You need to wait to be activated before being able to switch to a shibboleth account."))
294
        super(ShibbolethUserCreationForm, self).clean_email()
295
        return email
296

    
297

    
298
class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm,
299
                                        InvitedThirdPartyUserCreationForm):
300
    pass
301

    
302

    
303
class LoginForm(AuthenticationForm):
304
    username = forms.EmailField(label=_("Email"))
305
    recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
306
    recaptcha_response_field = forms.CharField(
307
        widget=RecaptchaWidget, label='')
308
    
309
    def __init__(self, *args, **kwargs):
310
        was_limited = kwargs.get('was_limited', False)
311
        request = kwargs.get('request', None)
312
        if request:
313
            self.ip = request.META.get('REMOTE_ADDR',
314
                                       request.META.get('HTTP_X_REAL_IP', None))
315

    
316
        t = ('request', 'was_limited')
317
        for elem in t:
318
            if elem in kwargs.keys():
319
                kwargs.pop(elem)
320
        super(LoginForm, self).__init__(*args, **kwargs)
321

    
322
        self.fields.keyOrder = ['username', 'password']
323
        if was_limited and RECAPTCHA_ENABLED:
324
            self.fields.keyOrder.extend(['recaptcha_challenge_field',
325
                                         'recaptcha_response_field', ])
326
    
327
    def clean_username(self):
328
        if 'username' in self.cleaned_data:
329
            return self.cleaned_data['username'].lower()
330
    
331
    def clean_recaptcha_response_field(self):
332
        if 'recaptcha_challenge_field' in self.cleaned_data:
333
            self.validate_captcha()
334
        return self.cleaned_data['recaptcha_response_field']
335

    
336
    def clean_recaptcha_challenge_field(self):
337
        if 'recaptcha_response_field' in self.cleaned_data:
338
            self.validate_captcha()
339
        return self.cleaned_data['recaptcha_challenge_field']
340

    
341
    def validate_captcha(self):
342
        rcf = self.cleaned_data['recaptcha_challenge_field']
343
        rrf = self.cleaned_data['recaptcha_response_field']
344
        check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
345
        if not check.is_valid:
346
            raise forms.ValidationError(
347
                _('You have not entered the correct words'))
348
    
349
    def clean(self):
350
        super(LoginForm, self).clean()
351
        if self.user_cache and self.user_cache.provider not in ('local', ''):
352
            raise forms.ValidationError(_('Local login is not the current authentication method for this account.'))
353
        return self.cleaned_data
354

    
355

    
356
class ProfileForm(forms.ModelForm):
357
    """
358
    Subclass of ``ModelForm`` for permiting user to edit his/her profile.
359
    Most of the fields are readonly since the user is not allowed to change
360
    them.
361

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

    
367
    class Meta:
368
        model = AstakosUser
369
        fields = ('email', 'first_name', 'last_name', 'auth_token',
370
                  'auth_token_expires')
371

    
372
    def __init__(self, *args, **kwargs):
373
        super(ProfileForm, self).__init__(*args, **kwargs)
374
        instance = getattr(self, 'instance', None)
375
        ro_fields = ('email', 'auth_token', 'auth_token_expires')
376
        if instance and instance.id:
377
            for field in ro_fields:
378
                self.fields[field].widget.attrs['readonly'] = True
379

    
380
    def save(self, commit=True):
381
        user = super(ProfileForm, self).save(commit=False)
382
        user.is_verified = True
383
        if self.cleaned_data.get('renew'):
384
            user.renew_token()
385
        if commit:
386
            user.save()
387
        return user
388

    
389

    
390
class FeedbackForm(forms.Form):
391
    """
392
    Form for writing feedback.
393
    """
394
    feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
395
    feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
396
                                    required=False)
397

    
398

    
399
class SendInvitationForm(forms.Form):
400
    """
401
    Form for sending an invitations
402
    """
403

    
404
    email = forms.EmailField(required=True, label='Email address')
405
    first_name = forms.EmailField(label='First name')
406
    last_name = forms.EmailField(label='Last name')
407

    
408

    
409
class ExtendedPasswordResetForm(PasswordResetForm):
410
    """
411
    Extends PasswordResetForm by overriding save method:
412
    passes a custom from_email in send_mail.
413

414
    Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
415
    accepts a from_email argument.
416
    """
417
    def clean_email(self):
418
        email = super(ExtendedPasswordResetForm, self).clean_email()
419
        try:
420
            user = AstakosUser.objects.get(email=email, is_active=True)
421
            if not user.has_usable_password():
422
                raise forms.ValidationError(
423
                    _("This account has not a usable password."))
424
        except AstakosUser.DoesNotExist:
425
            raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?'))
426
        return email
427

    
428
    def save(
429
        self, domain_override=None, email_template_name='registration/password_reset_email.html',
430
            use_https=False, token_generator=default_token_generator, request=None):
431
        """
432
        Generates a one-use only link for resetting password and sends to the user.
433
        """
434
        for user in self.users_cache:
435
            url = reverse('django.contrib.auth.views.password_reset_confirm',
436
                          kwargs={'uidb36': int_to_base36(user.id),
437
                                  'token': token_generator.make_token(user)
438
                                  }
439
                          )
440
            url = urljoin(BASEURL, url)
441
            t = loader.get_template(email_template_name)
442
            c = {
443
                'email': user.email,
444
                'url': url,
445
                'site_name': SITENAME,
446
                'user': user,
447
                'baseurl': BASEURL,
448
                'support': DEFAULT_CONTACT_EMAIL
449
            }
450
            from_email = settings.SERVER_EMAIL
451
            send_mail(_(PASSWORD_RESET_EMAIL_SUBJECT),
452
                      t.render(Context(c)), from_email, [user.email])
453

    
454

    
455
class EmailChangeForm(forms.ModelForm):
456
    class Meta:
457
        model = EmailChange
458
        fields = ('new_email_address',)
459

    
460
    def clean_new_email_address(self):
461
        addr = self.cleaned_data['new_email_address']
462
        if AstakosUser.objects.filter(email__iexact=addr):
463
            raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
464
        return addr
465

    
466
    def save(self, email_template_name, request, commit=True):
467
        ec = super(EmailChangeForm, self).save(commit=False)
468
        ec.user = request.user
469
        activation_key = hashlib.sha1(
470
            str(random()) + smart_str(ec.new_email_address))
471
        ec.activation_key = activation_key.hexdigest()
472
        if commit:
473
            ec.save()
474
        send_change_email(ec, request, email_template_name=email_template_name)
475

    
476

    
477
class SignApprovalTermsForm(forms.ModelForm):
478
    class Meta:
479
        model = AstakosUser
480
        fields = ("has_signed_terms",)
481

    
482
    def __init__(self, *args, **kwargs):
483
        super(SignApprovalTermsForm, self).__init__(*args, **kwargs)
484

    
485
    def clean_has_signed_terms(self):
486
        has_signed_terms = self.cleaned_data['has_signed_terms']
487
        if not has_signed_terms:
488
            raise forms.ValidationError(_('You have to agree with the terms'))
489
        return has_signed_terms
490

    
491

    
492
class InvitationForm(forms.ModelForm):
493
    username = forms.EmailField(label=_("Email"))
494

    
495
    def __init__(self, *args, **kwargs):
496
        super(InvitationForm, self).__init__(*args, **kwargs)
497

    
498
    class Meta:
499
        model = Invitation
500
        fields = ('username', 'realname')
501

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

    
512

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

    
523
    def __init__(self, user, *args, **kwargs):
524
        super(ExtendedPasswordChangeForm, self).__init__(user, *args, **kwargs)
525

    
526
    def save(self, commit=True):
527
        user = super(ExtendedPasswordChangeForm, self).save(commit=False)
528
        if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'):
529
            user.renew_token()
530
        if commit:
531
            user.save()
532
        return user
533

    
534

    
535
class AstakosGroupCreationForm(forms.ModelForm):
536
    kind = forms.ModelChoiceField(
537
        queryset=GroupKind.objects.all(),
538
        label="",
539
        widget=forms.HiddenInput()
540
    )
541
    name = forms.URLField()
542
    moderation_enabled = forms.BooleanField(
543
        help_text="Check if you want to approve members participation manually",
544
        required=False   
545
    )
546
    
547
    class Meta:
548
        model = AstakosGroup
549

    
550
    def __init__(self, *args, **kwargs):
551
        try:
552
            resources = kwargs.pop('resources')
553
        except KeyError:
554
            resources = {}
555
        super(AstakosGroupCreationForm, self).__init__(*args, **kwargs)
556
        self.fields.keyOrder = ['kind', 'name', 'homepage', 'desc', 'issue_date',
557
                                'expiration_date', 'estimated_participants',
558
                                'moderation_enabled']
559
        for id, r in resources.iteritems():
560
            self.fields['resource_%s' % id] = forms.IntegerField(
561
                label=r,
562
                required=False,
563
                help_text=_('Leave it blank for no additional quota.')
564
            )
565

    
566
    def resources(self):
567
        for name, value in self.cleaned_data.items():
568
            prefix, delimiter, suffix = name.partition('resource_')
569
            if suffix:
570
                # yield only those having a value
571
                if not value:
572
                    continue
573
                yield (suffix, value)
574

    
575
class AstakosGroupUpdateForm(forms.ModelForm):
576
    class Meta:
577
        model = AstakosGroup
578
        fields = ('homepage', 'desc')
579

    
580
class AddGroupMembersForm(forms.Form):
581
    q = forms.CharField(max_length=800, widget=forms.Textarea, label=_('Search users'),
582
                        help_text=_('Add comma separated user emails'),
583
                        required=True)
584
    
585
    def clean(self):
586
        q = self.cleaned_data.get('q') or ''
587
        users = q.split(',')
588
        users = list(u.strip() for u in users if u)
589
        db_entries = AstakosUser.objects.filter(email__in=users)
590
        unknown = list(set(users) - set(u.email for u in db_entries))
591
        if unknown:
592
            raise forms.ValidationError(
593
                _('Unknown users: %s' % ','.join(unknown)))
594
        self.valid_users = db_entries
595
        return self.cleaned_data
596
    
597
    def get_valid_users(self):
598
        """Should be called after form cleaning"""
599
        try:
600
            return self.valid_users
601
        except:
602
            return ()
603

    
604

    
605
class AstakosGroupSearchForm(forms.Form):
606
    q = forms.CharField(max_length=200, label='Search group')
607

    
608
class TimelineForm(forms.Form):
609
#    entity = forms.CharField(
610
#        widget=forms.HiddenInput(), label='')
611
    entity = forms.ModelChoiceField(
612
        queryset=AstakosUser.objects.filter(is_active = True)
613
    )
614
    resource = forms.ModelChoiceField(
615
        queryset=Resource.objects.all()
616
    )
617
    start_date = forms.DateTimeField()
618
    end_date = forms.DateTimeField()
619
    details = forms.BooleanField(required=False, label="Detailed Listing")
620
    operation = forms.ChoiceField(
621
                        label   = 'Charge Method',
622
                        choices = ( ('',                '-------------'),
623
                                    ('charge_usage',    'Charge Usage'),
624
                                    ('charge_traffic',  'Charge Traffic'), )
625
                )
626
    def clean(self):
627
        super(TimelineForm, self).clean()
628
        d = self.cleaned_data
629
        if 'resource' in d:
630
            d['resource'] = str(d['resource'])
631
        if 'start_date' in d:
632
            d['start_date'] = d['start_date'].strftime("%Y-%m-%dT%H:%M:%S.%f")[:24]
633
        if 'end_date' in d:
634
            d['end_date'] = d['end_date'].strftime("%Y-%m-%dT%H:%M:%S.%f")[:24]
635
        if 'entity' in d:
636
            d['entity'] = d['entity'].email 
637
        return d
638

    
639
class AstakosGroupSortForm(forms.Form):
640
    sort_by = forms.ChoiceField(label='Sort by',
641
                                choices=(('groupname', 'Name'),
642
                                         ('kindname', 'Type'),
643
                                         ('issue_date', 'Issue Date'),
644
                                         ('expiration_date', 'Expiration Date'),
645
                                         ('approved_members_num', 'Participants'),
646
                                         ('is_enabled', 'Status'),
647
                                         ('moderation_enabled', 'Moderation'),
648
                                         ('membership_status','Enrollment Status')
649
                                         ),
650
                                required=False)
651

    
652
class MembersSortForm(forms.Form):
653
    sort_by = forms.ChoiceField(label='Sort by',
654
                                choices=(('person__email', 'User Id'),
655
                                         ('person__first_name', 'Name'),
656
                                         ('date_joined', 'Status')
657
                                         ),
658
                                required=False)
659

    
660
class PickResourceForm(forms.Form):
661
    resource = forms.ModelChoiceField(
662
        queryset=Resource.objects.select_related().all()
663
    )
664
    resource.widget.attrs["onchange"]="this.form.submit()"
665

    
666
class ExtendedSetPasswordForm(SetPasswordForm):
667
    """
668
    Extends SetPasswordForm by enabling user
669
    to optionally renew also the token.
670
    """
671
    if not NEWPASSWD_INVALIDATE_TOKEN:
672
        renew = forms.BooleanField(label='Renew token', required=False,
673
                                   initial=True,
674
                                   help_text='Unsetting this may result in security risk.')
675
    
676
    def __init__(self, user, *args, **kwargs):
677
        super(ExtendedSetPasswordForm, self).__init__(user, *args, **kwargs)
678
    
679
    def save(self, commit=True):
680
        user = super(ExtendedSetPasswordForm, self).save(commit=False)
681
        if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'):
682
            try:
683
                user = AstakosUser.objects.get(id=user.id)
684
            except AstakosUser.DoesNotExist:
685
                pass
686
            else:
687
                user.renew_token()
688
        if commit:
689
            user.save()
690
        return user