Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / forms.py @ 40b52116

History | View | Annotate | Download (38.2 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 random import random
35

    
36
from django import forms
37
from django.utils.translation import ugettext as _
38
from django.contrib.auth.forms import (
39
    UserCreationForm, AuthenticationForm,
40
    PasswordResetForm, PasswordChangeForm,
41
    SetPasswordForm)
42
from django.core.mail import send_mail
43
from django.contrib.auth.tokens import default_token_generator
44
from django.template import Context, loader
45
from django.utils.http import int_to_base36
46
from django.core.urlresolvers import reverse
47
from django.utils.safestring import mark_safe
48
from django.utils.encoding import smart_str
49
from django.conf import settings
50
from django.forms.models import fields_for_model
51
from django.db import transaction
52
from django.utils.encoding import smart_unicode
53
from django.core import validators
54
from django.contrib.auth.models import AnonymousUser
55

    
56
from astakos.im.models import (
57
    AstakosUser, EmailChange, Invitation,
58
#     AstakosGroup, GroupKind,
59
    Resource, PendingThirdPartyUser, get_latest_terms, RESOURCE_SEPARATOR,
60
    ProjectApplication)
61
from astakos.im.settings import (
62
    INVITATIONS_PER_LEVEL, BASEURL, SITENAME, RECAPTCHA_PRIVATE_KEY,
63
    RECAPTCHA_ENABLED, DEFAULT_CONTACT_EMAIL, LOGGING_LEVEL,
64
    PASSWORD_RESET_EMAIL_SUBJECT, NEWPASSWD_INVALIDATE_TOKEN,
65
    MODERATION_ENABLED)
66
from astakos.im.widgets import DummyWidget, RecaptchaWidget
67
from astakos.im.functions import send_change_email, submit_application
68

    
69
from astakos.im.util import reserved_email, get_query
70
from astakos.im import auth_providers
71

    
72
import astakos.im.messages as astakos_messages
73

    
74
import logging
75
import hashlib
76
import recaptcha.client.captcha as captcha
77
import re
78

    
79
logger = logging.getLogger(__name__)
80

    
81
DOMAIN_VALUE_REGEX = re.compile(
82
    r'^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$',
83
    re.IGNORECASE)
84

    
85
class StoreUserMixin(object):
86

    
87
    @transaction.commit_on_success
88
    def store_user(self, user, request):
89
        user.save()
90
        self.post_store_user(user, request)
91
        return user
92

    
93
    def post_store_user(self, user, request):
94
        """
95
        Interface method for descendant backends to be able to do stuff within
96
        the transaction enabled by store_user.
97
        """
98
        pass
99

    
100

    
101
class LocalUserCreationForm(UserCreationForm, StoreUserMixin):
102
    """
103
    Extends the built in UserCreationForm in several ways:
104

105
    * Adds email, first_name, last_name, recaptcha_challenge_field, recaptcha_response_field field.
106
    * The username field isn't visible and it is assigned a generated id.
107
    * User created is not active.
108
    """
109
    recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
110
    recaptcha_response_field = forms.CharField(
111
        widget=RecaptchaWidget, label='')
112

    
113
    class Meta:
114
        model = AstakosUser
115
        fields = ("email", "first_name", "last_name",
116
                  "has_signed_terms", "has_signed_terms")
117

    
118
    def __init__(self, *args, **kwargs):
119
        """
120
        Changes the order of fields, and removes the username field.
121
        """
122
        request = kwargs.pop('request', None)
123
        if request:
124
            self.ip = request.META.get('REMOTE_ADDR',
125
                                       request.META.get('HTTP_X_REAL_IP', None))
126

    
127
        super(LocalUserCreationForm, self).__init__(*args, **kwargs)
128
        self.fields.keyOrder = ['email', 'first_name', 'last_name',
129
                                'password1', 'password2']
130

    
131
        if RECAPTCHA_ENABLED:
132
            self.fields.keyOrder.extend(['recaptcha_challenge_field',
133
                                         'recaptcha_response_field', ])
134
        if get_latest_terms():
135
            self.fields.keyOrder.append('has_signed_terms')
136

    
137
        if 'has_signed_terms' in self.fields:
138
            # Overriding field label since we need to apply a link
139
            # to the terms within the label
140
            terms_link_html = '<a href="%s" target="_blank">%s</a>' \
141
                % (reverse('latest_terms'), _("the terms"))
142
            self.fields['has_signed_terms'].label = \
143
                mark_safe("I agree with %s" % terms_link_html)
144

    
145
    def clean_email(self):
146
        email = self.cleaned_data['email']
147
        if not email:
148
            raise forms.ValidationError(_(astakos_messages.REQUIRED_FIELD))
149
        if reserved_email(email):
150
            raise forms.ValidationError(_(astakos_messages.EMAIL_USED))
151
        return email
152

    
153
    def clean_has_signed_terms(self):
154
        has_signed_terms = self.cleaned_data['has_signed_terms']
155
        if not has_signed_terms:
156
            raise forms.ValidationError(_(astakos_messages.SIGN_TERMS))
157
        return has_signed_terms
158

    
159
    def clean_recaptcha_response_field(self):
160
        if 'recaptcha_challenge_field' in self.cleaned_data:
161
            self.validate_captcha()
162
        return self.cleaned_data['recaptcha_response_field']
163

    
164
    def clean_recaptcha_challenge_field(self):
165
        if 'recaptcha_response_field' in self.cleaned_data:
166
            self.validate_captcha()
167
        return self.cleaned_data['recaptcha_challenge_field']
168

    
169
    def validate_captcha(self):
170
        rcf = self.cleaned_data['recaptcha_challenge_field']
171
        rrf = self.cleaned_data['recaptcha_response_field']
172
        check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
173
        if not check.is_valid:
174
            raise forms.ValidationError(_(astakos_messages.CAPTCHA_VALIDATION_ERR))
175

    
176
    def post_store_user(self, user, request):
177
        """
178
        Interface method for descendant backends to be able to do stuff within
179
        the transaction enabled by store_user.
180
        """
181
        user.add_auth_provider('local', auth_backend='astakos')
182
        user.set_password(self.cleaned_data['password1'])
183

    
184
    def save(self, commit=True):
185
        """
186
        Saves the email, first_name and last_name properties, after the normal
187
        save behavior is complete.
188
        """
189
        user = super(LocalUserCreationForm, self).save(commit=False)
190
        user.renew_token()
191
        if commit:
192
            user.save()
193
            logger.log(LOGGING_LEVEL, 'Created user %s' % user.email)
194
        return user
195

    
196

    
197
class InvitedLocalUserCreationForm(LocalUserCreationForm):
198
    """
199
    Extends the LocalUserCreationForm: email is readonly.
200
    """
201
    class Meta:
202
        model = AstakosUser
203
        fields = ("email", "first_name", "last_name", "has_signed_terms")
204

    
205
    def __init__(self, *args, **kwargs):
206
        """
207
        Changes the order of fields, and removes the username field.
208
        """
209
        super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs)
210

    
211
        #set readonly form fields
212
        ro = ('email', 'username',)
213
        for f in ro:
214
            self.fields[f].widget.attrs['readonly'] = True
215

    
216
    def save(self, commit=True):
217
        user = super(InvitedLocalUserCreationForm, self).save(commit=False)
218
        user.set_invitations_level()
219
        user.email_verified = True
220
        if commit:
221
            user.save()
222
        return user
223

    
224

    
225
class ThirdPartyUserCreationForm(forms.ModelForm, StoreUserMixin):
226
    id = forms.CharField(
227
        widget=forms.HiddenInput(),
228
        label='',
229
        required=False
230
    )
231
    third_party_identifier = forms.CharField(
232
        widget=forms.HiddenInput(),
233
        label=''
234
    )
235
    class Meta:
236
        model = AstakosUser
237
        fields = ['id', 'email', 'third_party_identifier', 'first_name', 'last_name']
238

    
239
    def __init__(self, *args, **kwargs):
240
        """
241
        Changes the order of fields, and removes the username field.
242
        """
243
        self.request = kwargs.get('request', None)
244
        if self.request:
245
            kwargs.pop('request')
246

    
247
        latest_terms = get_latest_terms()
248
        if latest_terms:
249
            self._meta.fields.append('has_signed_terms')
250

    
251
        super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
252

    
253
        if latest_terms:
254
            self.fields.keyOrder.append('has_signed_terms')
255

    
256
        if 'has_signed_terms' in self.fields:
257
            # Overriding field label since we need to apply a link
258
            # to the terms within the label
259
            terms_link_html = '<a href="%s" target="_blank">%s</a>' \
260
                % (reverse('latest_terms'), _("the terms"))
261
            self.fields['has_signed_terms'].label = \
262
                    mark_safe("I agree with %s" % terms_link_html)
263

    
264
    def clean_email(self):
265
        email = self.cleaned_data['email']
266
        if not email:
267
            raise forms.ValidationError(_(astakos_messages.REQUIRED_FIELD))
268
        if reserved_email(email):
269
            raise forms.ValidationError(_(astakos_messages.EMAIL_USED))
270
        return email
271

    
272
    def clean_has_signed_terms(self):
273
        has_signed_terms = self.cleaned_data['has_signed_terms']
274
        if not has_signed_terms:
275
            raise forms.ValidationError(_(astakos_messages.SIGN_TERMS))
276
        return has_signed_terms
277

    
278
    def post_store_user(self, user, request):
279
        pending = PendingThirdPartyUser.objects.get(
280
                                token=request.POST.get('third_party_token'),
281
                                third_party_identifier= \
282
            self.cleaned_data.get('third_party_identifier'))
283
        return user.add_pending_auth_provider(pending)
284

    
285

    
286
    def save(self, commit=True):
287
        user = super(ThirdPartyUserCreationForm, self).save(commit=False)
288
        user.set_unusable_password()
289
        user.renew_token()
290
        if commit:
291
            user.save()
292
            logger.log(LOGGING_LEVEL, 'Created user %s' % user.email)
293
        return user
294

    
295

    
296
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
297
    """
298
    Extends the ThirdPartyUserCreationForm: email is readonly.
299
    """
300
    def __init__(self, *args, **kwargs):
301
        """
302
        Changes the order of fields, and removes the username field.
303
        """
304
        super(
305
            InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
306

    
307
        #set readonly form fields
308
        ro = ('email',)
309
        for f in ro:
310
            self.fields[f].widget.attrs['readonly'] = True
311

    
312
    def save(self, commit=True):
313
        user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False)
314
        user.set_invitation_level()
315
        user.email_verified = True
316
        if commit:
317
            user.save()
318
        return user
319

    
320

    
321
class ShibbolethUserCreationForm(ThirdPartyUserCreationForm):
322
    additional_email = forms.CharField(
323
        widget=forms.HiddenInput(), label='', required=False)
324

    
325
    def __init__(self, *args, **kwargs):
326
        super(ShibbolethUserCreationForm, self).__init__(*args, **kwargs)
327
        # copy email value to additional_mail in case user will change it
328
        name = 'email'
329
        field = self.fields[name]
330
        self.initial['additional_email'] = self.initial.get(name, field.initial)
331
        self.initial['email'] = None
332

    
333

    
334
class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm,
335
                                        InvitedThirdPartyUserCreationForm):
336
    pass
337

    
338

    
339
class LoginForm(AuthenticationForm):
340
    username = forms.EmailField(label=_("Email"))
341
    recaptcha_challenge_field = forms.CharField(widget=DummyWidget)
342
    recaptcha_response_field = forms.CharField(
343
        widget=RecaptchaWidget, label='')
344

    
345
    def __init__(self, *args, **kwargs):
346
        was_limited = kwargs.get('was_limited', False)
347
        request = kwargs.get('request', None)
348
        if request:
349
            self.ip = request.META.get('REMOTE_ADDR',
350
                                       request.META.get('HTTP_X_REAL_IP', None))
351

    
352
        t = ('request', 'was_limited')
353
        for elem in t:
354
            if elem in kwargs.keys():
355
                kwargs.pop(elem)
356
        super(LoginForm, self).__init__(*args, **kwargs)
357

    
358
        self.fields.keyOrder = ['username', 'password']
359
        if was_limited and RECAPTCHA_ENABLED:
360
            self.fields.keyOrder.extend(['recaptcha_challenge_field',
361
                                         'recaptcha_response_field', ])
362

    
363
    def clean_username(self):
364
        return self.cleaned_data['username'].lower()
365

    
366
    def clean_recaptcha_response_field(self):
367
        if 'recaptcha_challenge_field' in self.cleaned_data:
368
            self.validate_captcha()
369
        return self.cleaned_data['recaptcha_response_field']
370

    
371
    def clean_recaptcha_challenge_field(self):
372
        if 'recaptcha_response_field' in self.cleaned_data:
373
            self.validate_captcha()
374
        return self.cleaned_data['recaptcha_challenge_field']
375

    
376
    def validate_captcha(self):
377
        rcf = self.cleaned_data['recaptcha_challenge_field']
378
        rrf = self.cleaned_data['recaptcha_response_field']
379
        check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
380
        if not check.is_valid:
381
            raise forms.ValidationError(_(astakos_messages.CAPTCHA_VALIDATION_ERR))
382

    
383
    def clean(self):
384
        """
385
        Override default behavior in order to check user's activation later
386
        """
387
        username = self.cleaned_data.get('username')
388

    
389
        if username:
390
            try:
391
                user = AstakosUser.objects.get_by_identifier(username)
392
                if not user.has_auth_provider('local'):
393
                    provider = auth_providers.get_provider('local')
394
                    raise forms.ValidationError(
395
                        _(provider.get_message('NOT_ACTIVE_FOR_USER')))
396
            except AstakosUser.DoesNotExist:
397
                pass
398

    
399
        try:
400
            super(LoginForm, self).clean()
401
        except forms.ValidationError, e:
402
            if self.user_cache is None:
403
                raise
404
            if not self.user_cache.is_active:
405
                raise forms.ValidationError(self.user_cache.get_inactive_message())
406
            if self.request:
407
                if not self.request.session.test_cookie_worked():
408
                    raise
409
        return self.cleaned_data
410

    
411

    
412
class ProfileForm(forms.ModelForm):
413
    """
414
    Subclass of ``ModelForm`` for permiting user to edit his/her profile.
415
    Most of the fields are readonly since the user is not allowed to change
416
    them.
417

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

    
423
    class Meta:
424
        model = AstakosUser
425
        fields = ('email', 'first_name', 'last_name', 'auth_token',
426
                  'auth_token_expires')
427

    
428
    def __init__(self, *args, **kwargs):
429
        self.session_key = kwargs.pop('session_key', None)
430
        super(ProfileForm, self).__init__(*args, **kwargs)
431
        instance = getattr(self, 'instance', None)
432
        ro_fields = ('email', 'auth_token', 'auth_token_expires')
433
        if instance and instance.id:
434
            for field in ro_fields:
435
                self.fields[field].widget.attrs['readonly'] = True
436

    
437
    def save(self, commit=True):
438
        user = super(ProfileForm, self).save(commit=False)
439
        user.is_verified = True
440
        if self.cleaned_data.get('renew'):
441
            user.renew_token(
442
                flush_sessions=True,
443
                current_key=self.session_key
444
            )
445
        if commit:
446
            user.save()
447
        return user
448

    
449

    
450
class FeedbackForm(forms.Form):
451
    """
452
    Form for writing feedback.
453
    """
454
    feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
455
    feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
456
                                    required=False)
457

    
458

    
459
class SendInvitationForm(forms.Form):
460
    """
461
    Form for sending an invitations
462
    """
463

    
464
    email = forms.EmailField(required=True, label='Email address')
465
    first_name = forms.EmailField(label='First name')
466
    last_name = forms.EmailField(label='Last name')
467

    
468

    
469
class ExtendedPasswordResetForm(PasswordResetForm):
470
    """
471
    Extends PasswordResetForm by overriding save method:
472
    passes a custom from_email in send_mail.
473

474
    Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
475
    accepts a from_email argument.
476
    """
477
    def clean_email(self):
478
        email = super(ExtendedPasswordResetForm, self).clean_email()
479
        try:
480
            user = AstakosUser.objects.get(email__iexact=email)
481
            if not user.has_usable_password():
482
                raise forms.ValidationError(_(astakos_messages.UNUSABLE_PASSWORD))
483

    
484
            if not user.can_change_password():
485
                raise forms.ValidationError(_('Password change for this account'
486
                                              ' is not supported.'))
487

    
488
        except AstakosUser.DoesNotExist, e:
489
            raise forms.ValidationError(_(astakos_messages.EMAIL_UNKNOWN))
490
        return email
491

    
492
    def save(
493
        self, domain_override=None, email_template_name='registration/password_reset_email.html',
494
            use_https=False, token_generator=default_token_generator, request=None):
495
        """
496
        Generates a one-use only link for resetting password and sends to the user.
497
        """
498
        for user in self.users_cache:
499
            url = user.astakosuser.get_password_reset_url(token_generator)
500
            url = urljoin(BASEURL, url)
501
            t = loader.get_template(email_template_name)
502
            c = {
503
                'email': user.email,
504
                'url': url,
505
                'site_name': SITENAME,
506
                'user': user,
507
                'baseurl': BASEURL,
508
                'support': DEFAULT_CONTACT_EMAIL
509
            }
510
            from_email = settings.SERVER_EMAIL
511
            send_mail(_(PASSWORD_RESET_EMAIL_SUBJECT),
512
                      t.render(Context(c)), from_email, [user.email])
513

    
514

    
515
class EmailChangeForm(forms.ModelForm):
516

    
517
    class Meta:
518
        model = EmailChange
519
        fields = ('new_email_address',)
520

    
521
    def clean_new_email_address(self):
522
        addr = self.cleaned_data['new_email_address']
523
        if AstakosUser.objects.filter(email__iexact=addr):
524
            raise forms.ValidationError(_(astakos_messages.EMAIL_USED))
525
        return addr
526

    
527
    def save(self, email_template_name, request, commit=True):
528
        ec = super(EmailChangeForm, self).save(commit=False)
529
        ec.user = request.user
530
        activation_key = hashlib.sha1(
531
            str(random()) + smart_str(ec.new_email_address))
532
        ec.activation_key = activation_key.hexdigest()
533
        if commit:
534
            ec.save()
535
        send_change_email(ec, request, email_template_name=email_template_name)
536

    
537

    
538
class SignApprovalTermsForm(forms.ModelForm):
539

    
540
    class Meta:
541
        model = AstakosUser
542
        fields = ("has_signed_terms",)
543

    
544
    def __init__(self, *args, **kwargs):
545
        super(SignApprovalTermsForm, self).__init__(*args, **kwargs)
546

    
547
    def clean_has_signed_terms(self):
548
        has_signed_terms = self.cleaned_data['has_signed_terms']
549
        if not has_signed_terms:
550
            raise forms.ValidationError(_(astakos_messages.SIGN_TERMS))
551
        return has_signed_terms
552

    
553

    
554
class InvitationForm(forms.ModelForm):
555

    
556
    username = forms.EmailField(label=_("Email"))
557

    
558
    def __init__(self, *args, **kwargs):
559
        super(InvitationForm, self).__init__(*args, **kwargs)
560

    
561
    class Meta:
562
        model = Invitation
563
        fields = ('username', 'realname')
564

    
565
    def clean_username(self):
566
        username = self.cleaned_data['username']
567
        try:
568
            Invitation.objects.get(username=username)
569
            raise forms.ValidationError(_(astakos_messages.INVITATION_EMAIL_EXISTS))
570
        except Invitation.DoesNotExist:
571
            pass
572
        return username
573

    
574

    
575
class ExtendedPasswordChangeForm(PasswordChangeForm):
576
    """
577
    Extends PasswordChangeForm by enabling user
578
    to optionally renew also the token.
579
    """
580
    if not NEWPASSWD_INVALIDATE_TOKEN:
581
        renew = forms.BooleanField(label='Renew token', required=False,
582
                                   initial=True,
583
                                   help_text='Unsetting this may result in security risk.')
584

    
585
    def __init__(self, user, *args, **kwargs):
586
        self.session_key = kwargs.pop('session_key', None)
587
        super(ExtendedPasswordChangeForm, self).__init__(user, *args, **kwargs)
588

    
589
    def save(self, commit=True):
590
        try:
591
            if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'):
592
                self.user.renew_token()
593
            self.user.flush_sessions(current_key=self.session_key)
594
        except AttributeError:
595
            # if user model does has not such methods
596
            pass
597
        return super(ExtendedPasswordChangeForm, self).save(commit=commit)
598

    
599

    
600
# class AstakosGroupCreationForm(forms.ModelForm):
601
#     kind = forms.ModelChoiceField(
602
#         queryset=GroupKind.objects.all(),
603
#         label="",
604
#         widget=forms.HiddenInput()
605
#     )
606
#     name = forms.CharField(
607
#         validators=[validators.RegexValidator(
608
#             DOMAIN_VALUE_REGEX,
609
#             _(astakos_messages.DOMAIN_VALUE_ERR), 'invalid'
610
#         )],
611
#         widget=forms.TextInput(attrs={'placeholder': 'myproject.mylab.ntua.gr'}),
612
#         help_text=" The Project's name should be in a domain format. The domain shouldn't neccessarily exist in the real world but is helpful to imply a structure. e.g.: myproject.mylab.ntua.gr or myservice.myteam.myorganization "
613
#     )
614
#     homepage = forms.URLField(
615
#         label= 'Homepage Url',
616
#         widget=forms.TextInput(attrs={'placeholder': 'http://myproject.com'}),
617
#         help_text="This should be a URL pointing at your project's site. e.g.: http://myproject.com ",
618
#         required=False
619
#     )
620
#     desc = forms.CharField(
621
#         label= 'Description',
622
#         widget=forms.Textarea, 
623
#         help_text= "Please provide a short but descriptive abstract of your Project, so that anyone searching can quickly understand what this Project is about. "
624
#     )
625
#     issue_date = forms.DateTimeField(
626
#         label= 'Start date',
627
#         help_text= "Here you specify the date you want your Project to start granting its resources. Its members will get the resources coming from this Project on this exact date."
628
#     )
629
#     expiration_date = forms.DateTimeField(
630
#         label= 'End date',
631
#         help_text= "Here you specify the date you want your Project to cease. This means that after this date all members will no longer be able to allocate resources from this Project.  "
632
#     )
633
#     moderation_enabled = forms.BooleanField(
634
#         label= 'Moderated',
635
#         help_text="Select this to approve each member manually, before they become a part of your Project (default). Be sure you know what you are doing, if you uncheck this option. ",
636
#         required=False,
637
#         initial=True
638
#     )
639
#     max_participants = forms.IntegerField(
640
#         label='Total number of members',
641
#         required=True, min_value=1,
642
#         help_text="Here you specify the number of members this Project is going to have. This means that this number of people will be granted the resources you will specify in the next step. This can be '1' if you are the only one wanting to get resources. "
643
#     )
644
# 
645
#     class Meta:
646
#         model = AstakosGroup
647
# 
648
#     def __init__(self, *args, **kwargs):
649
#         #update QueryDict
650
#         args = list(args)
651
#         qd = args.pop(0).copy()
652
#         members_unlimited = qd.pop('members_unlimited', False)
653
#         members_uplimit = qd.pop('members_uplimit', None)
654
# 
655
#         #substitue QueryDict
656
#         args.insert(0, qd)
657
# 
658
#         super(AstakosGroupCreationForm, self).__init__(*args, **kwargs)
659
#         
660
#         self.fields.keyOrder = ['kind', 'name', 'homepage', 'desc',
661
#                                 'issue_date', 'expiration_date',
662
#                                 'moderation_enabled', 'max_participants']
663
#         def add_fields((k, v)):
664
#             k = k.partition('_proxy')[0]
665
#             self.fields[k] = forms.IntegerField(
666
#                 required=False,
667
#                 widget=forms.HiddenInput(),
668
#                 min_value=1
669
#             )
670
#         map(add_fields,
671
#             ((k, v) for k,v in qd.iteritems() if k.endswith('_uplimit'))
672
#         )
673
# 
674
#         def add_fields((k, v)):
675
#             self.fields[k] = forms.BooleanField(
676
#                 required=False,
677
#                 #widget=forms.HiddenInput()
678
#             )
679
#         map(add_fields,
680
#             ((k, v) for k,v in qd.iteritems() if k.startswith('is_selected_'))
681
#         )
682
# 
683
#     def policies(self):
684
#         self.clean()
685
#         policies = []
686
#         append = policies.append
687
#         for name, uplimit in self.cleaned_data.iteritems():
688
# 
689
#             subs = name.split('_uplimit')
690
#             if len(subs) == 2:
691
#                 prefix, suffix = subs
692
#                 s, sep, r = prefix.partition(RESOURCE_SEPARATOR)
693
#                 resource = Resource.objects.get(service__name=s, name=r)
694
# 
695
#                 # keep only resource limits for selected resource groups
696
#                 if self.cleaned_data.get(
697
#                     'is_selected_%s' % resource.group, False
698
#                 ):
699
#                     append(dict(service=s, resource=r, uplimit=uplimit))
700
#         return policies
701
# 
702
# class AstakosGroupCreationSummaryForm(forms.ModelForm):
703
#     kind = forms.ModelChoiceField(
704
#         queryset=GroupKind.objects.all(),
705
#         label="",
706
#         widget=forms.HiddenInput()
707
#     )
708
#     name = forms.CharField(
709
#         widget=forms.TextInput(attrs={'placeholder': 'eg. foo.ece.ntua.gr'}),
710
#         help_text="Name should be in the form of dns"
711
#     )
712
#     moderation_enabled = forms.BooleanField(
713
#         help_text="Check if you want to approve members participation manually",
714
#         required=False,
715
#         initial=True
716
#     )
717
#     max_participants = forms.IntegerField(
718
#         required=False, min_value=1
719
#     )
720
# 
721
#     class Meta:
722
#         model = AstakosGroup
723
# 
724
#     def __init__(self, *args, **kwargs):
725
#         #update QueryDict
726
#         args = list(args)
727
#         qd = args.pop(0).copy()
728
#         members_unlimited = qd.pop('members_unlimited', False)
729
#         members_uplimit = qd.pop('members_uplimit', None)
730
# 
731
#         #substitue QueryDict
732
#         args.insert(0, qd)
733
# 
734
#         super(AstakosGroupCreationSummaryForm, self).__init__(*args, **kwargs)
735
#         self.fields.keyOrder = ['kind', 'name', 'homepage', 'desc',
736
#                                 'issue_date', 'expiration_date',
737
#                                 'moderation_enabled', 'max_participants']
738
#         def add_fields((k, v)):
739
#             self.fields[k] = forms.IntegerField(
740
#                 required=False,
741
#                 widget=forms.TextInput(),
742
#                 min_value=1
743
#             )
744
#         map(add_fields,
745
#             ((k, v) for k,v in qd.iteritems() if k.endswith('_uplimit'))
746
#         )
747
# 
748
#         def add_fields((k, v)):
749
#             self.fields[k] = forms.BooleanField(
750
#                 required=False,
751
#                 widget=forms.HiddenInput()
752
#             )
753
#         map(add_fields,
754
#             ((k, v) for k,v in qd.iteritems() if k.startswith('is_selected_'))
755
#         )
756
#         for f in self.fields.values():
757
#             f.widget = forms.HiddenInput()
758
# 
759
#     def clean(self):
760
#         super(AstakosGroupCreationSummaryForm, self).clean()
761
#         self.cleaned_data['policies'] = []
762
#         append = self.cleaned_data['policies'].append
763
#         #tbd = [f for f in self.fields if (f.startswith('is_selected_') and (not f.endswith('_proxy')))]
764
#         tbd = [f for f in self.fields if f.startswith('is_selected_')]
765
#         for name, uplimit in self.cleaned_data.iteritems():
766
#             subs = name.split('_uplimit')
767
#             if len(subs) == 2:
768
#                 tbd.append(name)
769
#                 prefix, suffix = subs
770
#                 s, sep, r = prefix.partition(RESOURCE_SEPARATOR)
771
#                 resource = Resource.objects.get(service__name=s, name=r)
772
# 
773
#                 # keep only resource limits for selected resource groups
774
#                 if self.cleaned_data.get(
775
#                     'is_selected_%s' % resource.group, False
776
#                 ):
777
#                     append(dict(service=s, resource=r, uplimit=uplimit))
778
#         for name in tbd:
779
#             self.cleaned_data.pop(name, None)
780
#         return self.cleaned_data
781
# 
782
# class AstakosGroupUpdateForm(forms.ModelForm):
783
#     class Meta:
784
#         model = AstakosGroup
785
#         fields = ( 'desc','homepage', 'moderation_enabled')
786
# 
787
# 
788
# class AddGroupMembersForm(forms.Form):
789
#     q = forms.CharField(
790
#         max_length=800, widget=forms.Textarea, label=_('Add members'),
791
#         help_text=_(astakos_messages.ADD_GROUP_MEMBERS_Q_HELP),
792
#         required=True)
793
# 
794
#     def clean(self):
795
#         q = self.cleaned_data.get('q') or ''
796
#         users = q.split(',')
797
#         users = list(u.strip() for u in users if u)
798
#         db_entries = AstakosUser.objects.filter(email__in=users)
799
#         unknown = list(set(users) - set(u.email for u in db_entries))
800
#         if unknown:
801
#             raise forms.ValidationError(_(astakos_messages.UNKNOWN_USERS) % ','.join(unknown))
802
#         self.valid_users = db_entries
803
#         return self.cleaned_data
804
# 
805
#     def get_valid_users(self):
806
#         """Should be called after form cleaning"""
807
#         try:
808
#             return self.valid_users
809
#         except:
810
#             return ()
811
# 
812
# 
813
# class AstakosGroupSearchForm(forms.Form):
814
#     q = forms.CharField(max_length=200, label='Search project')
815
# 
816
# 
817
# class TimelineForm(forms.Form):
818
#     entity = forms.ModelChoiceField(
819
#         queryset=AstakosUser.objects.filter(is_active=True)
820
#     )
821
#     resource = forms.ModelChoiceField(
822
#         queryset=Resource.objects.all()
823
#     )
824
#     start_date = forms.DateTimeField()
825
#     end_date = forms.DateTimeField()
826
#     details = forms.BooleanField(required=False, label="Detailed Listing")
827
#     operation = forms.ChoiceField(
828
#         label='Charge Method',
829
#         choices=(('', '-------------'),
830
#                  ('charge_usage', 'Charge Usage'),
831
#                  ('charge_traffic', 'Charge Traffic'), )
832
#     )
833
# 
834
#     def clean(self):
835
#         super(TimelineForm, self).clean()
836
#         d = self.cleaned_data
837
#         if 'resource' in d:
838
#             d['resource'] = str(d['resource'])
839
#         if 'start_date' in d:
840
#             d['start_date'] = d['start_date'].strftime(
841
#                 "%Y-%m-%dT%H:%M:%S.%f")[:24]
842
#         if 'end_date' in d:
843
#             d['end_date'] = d['end_date'].strftime("%Y-%m-%dT%H:%M:%S.%f")[:24]
844
#         if 'entity' in d:
845
#             d['entity'] = d['entity'].email
846
#         return d
847
# 
848
# 
849
# class AstakosGroupSortForm(forms.Form):
850
#     sorting = forms.ChoiceField(
851
#         label='Sort by',
852
#         choices=(
853
#             ('groupname', 'Name'),
854
#             ('issue_date', 'Issue Date'),
855
#             ('expiration_date', 'Expiration Date'),
856
#             ('approved_members_num', 'Participants'),
857
#             ('moderation_enabled', 'Moderation'),
858
#             ('membership_status', 'Enrollment Status')
859
#         ),
860
#         required=True
861
#     )
862
# 
863
# class MembersSortForm(forms.Form):
864
#     sorting = forms.ChoiceField(
865
#         label='Sort by',
866
#         choices=(('person__email', 'User Id'),
867
#                  ('person__first_name', 'Name'),
868
#                  ('date_joined', 'Status')
869
#         ),
870
#         required=True
871
#     )
872
# 
873
# class PickResourceForm(forms.Form):
874
#     resource = forms.ModelChoiceField(
875
#         queryset=Resource.objects.select_related().all()
876
#     )
877
#     resource.widget.attrs["onchange"] = "this.form.submit()"
878

    
879

    
880
class ExtendedSetPasswordForm(SetPasswordForm):
881
    """
882
    Extends SetPasswordForm by enabling user
883
    to optionally renew also the token.
884
    """
885
    if not NEWPASSWD_INVALIDATE_TOKEN:
886
        renew = forms.BooleanField(
887
            label='Renew token',
888
            required=False,
889
            initial=True,
890
            help_text='Unsetting this may result in security risk.')
891

    
892
    def __init__(self, user, *args, **kwargs):
893
        super(ExtendedSetPasswordForm, self).__init__(user, *args, **kwargs)
894

    
895
    @transaction.commit_on_success()
896
    def save(self, commit=True):
897
        try:
898
            self.user = AstakosUser.objects.get(id=self.user.id)
899
            if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'):
900
                self.user.renew_token()
901
            #self.user.flush_sessions()
902
            if not self.user.has_auth_provider('local'):
903
                self.user.add_auth_provider('local', auth_backend='astakos')
904

    
905
        except BaseException, e:
906
            logger.exception(e)
907
        return super(ExtendedSetPasswordForm, self).save(commit=commit)
908

    
909

    
910
class ProjectApplicationForm(forms.ModelForm):
911
    name = forms.CharField(
912
        validators=[validators.RegexValidator(
913
            DOMAIN_VALUE_REGEX,
914
            _(astakos_messages.DOMAIN_VALUE_ERR),
915
            'invalid'
916
        )],
917
        widget=forms.TextInput(attrs={'placeholder': 'eg. foo.ece.ntua.gr'}),
918
        help_text="Name should be in the form of dns"
919
    )
920
    comments = forms.CharField(widget=forms.Textarea, required=False)
921
    
922
    class Meta:
923
        model = ProjectApplication
924
        exclude = (
925
            'project',
926
            'resource_grants', 'id', 'applicant', 'owner',
927
            'precursor_application', 'state', 'issue_date')
928

    
929
    def __init__(self, *args, **kwargs):
930
        self.precursor_application = kwargs.get('instance')
931
        super(ProjectApplicationForm, self).__init__(*args, **kwargs)
932
    
933
    def clean(self):
934
        userid = self.data.get('user', None)
935
        self.user = None
936
        if userid:
937
            try:
938
                self.user = AstakosUser.objects.get(id=userid)
939
            except AstakosUser.DoesNotExist:
940
                pass
941
        if not self.user:
942
            raise forms.ValidationError(_(astakos_messages.NO_APPLICANT))
943
        super(ProjectApplicationForm, self).clean()
944
        return self.cleaned_data
945
    
946
    @property
947
    def resource_policies(self):
948
        policies = []
949
        append = policies.append
950
        for name, value in self.data.iteritems():
951
            if not value:
952
                continue
953
            uplimit = value
954
            if name.endswith('_uplimit'):
955
                subs = name.split('_uplimit')
956
                prefix, suffix = subs
957
                s, sep, r = prefix.partition(RESOURCE_SEPARATOR)
958
                resource = Resource.objects.get(service__name=s, name=r)
959

    
960
                # keep only resource limits for selected resource groups
961
#                 if self.data.get(
962
#                     'is_selected_%s' % resource.group, False
963
#                 ):
964
                if uplimit:
965
                    append(dict(service=s, resource=r, uplimit=uplimit))
966
        return policies
967

    
968
    def save(self, commit=True):
969
        application = super(ProjectApplicationForm, self).save(commit=False)
970
        applicant = self.user
971
        comments = self.cleaned_data.pop('comments', None)
972
        return submit_application(
973
            application,
974
            self.resource_policies,
975
            applicant,
976
            comments,
977
            self.precursor_application
978
        )
979

    
980
class ProjectSortForm(forms.Form):
981
    sorting = forms.ChoiceField(
982
        label='Sort by',
983
        choices=(('name', 'Sort by Name'),
984
                 ('issue_date', 'Sort by Issue date'),
985
                 ('start_date', 'Sort by Start Date'),
986
                 ('end_date', 'Sort by End Date'),
987
#                  ('approved_members_num', 'Sort by Participants'),
988
                 ('state', 'Sort by Status'),
989
                 ('member_join_policy__description', 'Sort by Member Join Policy'),
990
                 ('member_leave_policy__description', 'Sort by Member Leave Policy'),
991
                 ('-name', 'Sort by Name'),
992
                 ('-issue_date', 'Sort by Issue date'),
993
                 ('-start_date', 'Sort by Start Date'),
994
                 ('-end_date', 'Sort by End Date'),
995
#                  ('-approved_members_num', 'Sort by Participants'),
996
                 ('-state', 'Sort by Status'),
997
                 ('-member_join_policy__description', 'Sort by Member Join Policy'),
998
                 ('-member_leave_policy__description', 'Sort by Member Leave Policy')
999
        ),
1000
        required=True
1001
    )
1002

    
1003
class AddProjectMembersForm(forms.Form):
1004
    q = forms.CharField(
1005
        max_length=800, widget=forms.Textarea, label=_('Add members'),
1006
        help_text=_(astakos_messages.ADD_PROJECT_MEMBERS_Q_HELP),
1007
        required=True)
1008

    
1009
    def clean(self):
1010
        q = self.cleaned_data.get('q') or ''
1011
        users = q.split(',')
1012
        users = list(u.strip() for u in users if u)
1013
        db_entries = AstakosUser.objects.filter(email__in=users)
1014
        unknown = list(set(users) - set(u.email for u in db_entries))
1015
        if unknown:
1016
            raise forms.ValidationError(_(astakos_messages.UNKNOWN_USERS) % ','.join(unknown))
1017
        self.valid_users = db_entries
1018
        return self.cleaned_data
1019

    
1020
    def get_valid_users(self):
1021
        """Should be called after form cleaning"""
1022
        try:
1023
            return self.valid_users
1024
        except:
1025
            return ()
1026

    
1027
class ProjectMembersSortForm(forms.Form):
1028
    sorting = forms.ChoiceField(
1029
        label='Sort by',
1030
        choices=(('person__email', 'User Id'),
1031
                 ('person__first_name', 'Name'),
1032
                 ('acceptance_date', 'Acceptance date')
1033
        ),
1034
        required=True
1035
    )
1036

    
1037
class ProjectSearchForm(forms.Form):
1038
    q = forms.CharField(max_length=200, label='Search project')