root / snf-astakos-app / astakos / im / forms.py @ f46c95c4
History | View | Annotate | Download (26.4 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 |
) |
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, RESOURCE_SEPARATOR) |
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, InvitedThirdPartyUserCreationForm): |
299 |
pass
|
300 |
|
301 |
|
302 |
class LoginForm(AuthenticationForm): |
303 |
username = forms.EmailField(label=_("Email"))
|
304 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
305 |
recaptcha_response_field = forms.CharField( |
306 |
widget=RecaptchaWidget, label='')
|
307 |
|
308 |
def __init__(self, *args, **kwargs): |
309 |
was_limited = kwargs.get('was_limited', False) |
310 |
request = kwargs.get('request', None) |
311 |
if request:
|
312 |
self.ip = request.META.get('REMOTE_ADDR', |
313 |
request.META.get('HTTP_X_REAL_IP', None)) |
314 |
|
315 |
t = ('request', 'was_limited') |
316 |
for elem in t: |
317 |
if elem in kwargs.keys(): |
318 |
kwargs.pop(elem) |
319 |
super(LoginForm, self).__init__(*args, **kwargs) |
320 |
|
321 |
self.fields.keyOrder = ['username', 'password'] |
322 |
if was_limited and RECAPTCHA_ENABLED: |
323 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
324 |
'recaptcha_response_field', ])
|
325 |
|
326 |
def clean_username(self): |
327 |
if 'username' in self.cleaned_data: |
328 |
return self.cleaned_data['username'].lower() |
329 |
|
330 |
def clean_recaptcha_response_field(self): |
331 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
332 |
self.validate_captcha()
|
333 |
return self.cleaned_data['recaptcha_response_field'] |
334 |
|
335 |
def clean_recaptcha_challenge_field(self): |
336 |
if 'recaptcha_response_field' in self.cleaned_data: |
337 |
self.validate_captcha()
|
338 |
return self.cleaned_data['recaptcha_challenge_field'] |
339 |
|
340 |
def validate_captcha(self): |
341 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
342 |
rrf = self.cleaned_data['recaptcha_response_field'] |
343 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
344 |
if not check.is_valid: |
345 |
raise forms.ValidationError(
|
346 |
_('You have not entered the correct words'))
|
347 |
|
348 |
def clean(self): |
349 |
super(LoginForm, self).clean() |
350 |
if self.user_cache and self.user_cache.provider not in ('local', ''): |
351 |
raise forms.ValidationError(_('Local login is not the current authentication method for this account.')) |
352 |
return self.cleaned_data |
353 |
|
354 |
|
355 |
class ProfileForm(forms.ModelForm): |
356 |
"""
|
357 |
Subclass of ``ModelForm`` for permiting user to edit his/her profile.
|
358 |
Most of the fields are readonly since the user is not allowed to change them.
|
359 |
|
360 |
The class defines a save method which sets ``is_verified`` to True so as the user
|
361 |
during the next login will not to be redirected to profile page.
|
362 |
"""
|
363 |
renew = forms.BooleanField(label='Renew token', required=False) |
364 |
|
365 |
class Meta: |
366 |
model = AstakosUser |
367 |
fields = ('email', 'first_name', 'last_name', 'auth_token', |
368 |
'auth_token_expires')
|
369 |
|
370 |
def __init__(self, *args, **kwargs): |
371 |
super(ProfileForm, self).__init__(*args, **kwargs) |
372 |
instance = getattr(self, 'instance', None) |
373 |
ro_fields = ('email', 'auth_token', 'auth_token_expires') |
374 |
if instance and instance.id: |
375 |
for field in ro_fields: |
376 |
self.fields[field].widget.attrs['readonly'] = True |
377 |
|
378 |
def save(self, commit=True): |
379 |
user = super(ProfileForm, self).save(commit=False) |
380 |
user.is_verified = True
|
381 |
if self.cleaned_data.get('renew'): |
382 |
user.renew_token() |
383 |
if commit:
|
384 |
user.save() |
385 |
return user
|
386 |
|
387 |
|
388 |
class FeedbackForm(forms.Form): |
389 |
"""
|
390 |
Form for writing feedback.
|
391 |
"""
|
392 |
feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
|
393 |
feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
|
394 |
required=False)
|
395 |
|
396 |
|
397 |
class SendInvitationForm(forms.Form): |
398 |
"""
|
399 |
Form for sending an invitations
|
400 |
"""
|
401 |
|
402 |
email = forms.EmailField(required=True, label='Email address') |
403 |
first_name = forms.EmailField(label='First name')
|
404 |
last_name = forms.EmailField(label='Last name')
|
405 |
|
406 |
|
407 |
class ExtendedPasswordResetForm(PasswordResetForm): |
408 |
"""
|
409 |
Extends PasswordResetForm by overriding save method:
|
410 |
passes a custom from_email in send_mail.
|
411 |
|
412 |
Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
|
413 |
accepts a from_email argument.
|
414 |
"""
|
415 |
def clean_email(self): |
416 |
email = super(ExtendedPasswordResetForm, self).clean_email() |
417 |
try:
|
418 |
user = AstakosUser.objects.get(email=email, is_active=True)
|
419 |
if not user.has_usable_password(): |
420 |
raise forms.ValidationError(
|
421 |
_("This account has not a usable password."))
|
422 |
except AstakosUser.DoesNotExist:
|
423 |
raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?')) |
424 |
return email
|
425 |
|
426 |
def save( |
427 |
self, domain_override=None, email_template_name='registration/password_reset_email.html', |
428 |
use_https=False, token_generator=default_token_generator, request=None): |
429 |
"""
|
430 |
Generates a one-use only link for resetting password and sends to the user.
|
431 |
"""
|
432 |
for user in self.users_cache: |
433 |
url = reverse('django.contrib.auth.views.password_reset_confirm',
|
434 |
kwargs={'uidb36': int_to_base36(user.id),
|
435 |
'token': token_generator.make_token(user)
|
436 |
} |
437 |
) |
438 |
url = urljoin(BASEURL, url) |
439 |
t = loader.get_template(email_template_name) |
440 |
c = { |
441 |
'email': user.email,
|
442 |
'url': url,
|
443 |
'site_name': SITENAME,
|
444 |
'user': user,
|
445 |
'baseurl': BASEURL,
|
446 |
'support': DEFAULT_CONTACT_EMAIL
|
447 |
} |
448 |
from_email = settings.SERVER_EMAIL |
449 |
send_mail(_(PASSWORD_RESET_EMAIL_SUBJECT), |
450 |
t.render(Context(c)), from_email, [user.email]) |
451 |
|
452 |
|
453 |
class EmailChangeForm(forms.ModelForm): |
454 |
class Meta: |
455 |
model = EmailChange |
456 |
fields = ('new_email_address',)
|
457 |
|
458 |
def clean_new_email_address(self): |
459 |
addr = self.cleaned_data['new_email_address'] |
460 |
if AstakosUser.objects.filter(email__iexact=addr):
|
461 |
raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.')) |
462 |
return addr
|
463 |
|
464 |
def save(self, email_template_name, request, commit=True): |
465 |
ec = super(EmailChangeForm, self).save(commit=False) |
466 |
ec.user = request.user |
467 |
activation_key = hashlib.sha1( |
468 |
str(random()) + smart_str(ec.new_email_address))
|
469 |
ec.activation_key = activation_key.hexdigest() |
470 |
if commit:
|
471 |
ec.save() |
472 |
send_change_email(ec, request, email_template_name=email_template_name) |
473 |
|
474 |
|
475 |
class SignApprovalTermsForm(forms.ModelForm): |
476 |
class Meta: |
477 |
model = AstakosUser |
478 |
fields = ("has_signed_terms",)
|
479 |
|
480 |
def __init__(self, *args, **kwargs): |
481 |
super(SignApprovalTermsForm, self).__init__(*args, **kwargs) |
482 |
|
483 |
def clean_has_signed_terms(self): |
484 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
485 |
if not has_signed_terms: |
486 |
raise forms.ValidationError(_('You have to agree with the terms')) |
487 |
return has_signed_terms
|
488 |
|
489 |
|
490 |
class InvitationForm(forms.ModelForm): |
491 |
username = forms.EmailField(label=_("Email"))
|
492 |
|
493 |
def __init__(self, *args, **kwargs): |
494 |
super(InvitationForm, self).__init__(*args, **kwargs) |
495 |
|
496 |
class Meta: |
497 |
model = Invitation |
498 |
fields = ('username', 'realname') |
499 |
|
500 |
def clean_username(self): |
501 |
username = self.cleaned_data['username'] |
502 |
try:
|
503 |
Invitation.objects.get(username=username) |
504 |
raise forms.ValidationError(
|
505 |
_('There is already invitation for this email.'))
|
506 |
except Invitation.DoesNotExist:
|
507 |
pass
|
508 |
return username
|
509 |
|
510 |
|
511 |
class ExtendedPasswordChangeForm(PasswordChangeForm): |
512 |
"""
|
513 |
Extends PasswordChangeForm by enabling user
|
514 |
to optionally renew also the token.
|
515 |
"""
|
516 |
renew = forms.BooleanField(label='Renew token', required=False) |
517 |
|
518 |
def __init__(self, user, *args, **kwargs): |
519 |
super(ExtendedPasswordChangeForm, self).__init__(user, *args, **kwargs) |
520 |
|
521 |
def save(self, commit=True): |
522 |
if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'): |
523 |
self.user.renew_token()
|
524 |
return super(ExtendedPasswordChangeForm, self).save(commit=commit) |
525 |
|
526 |
|
527 |
class AstakosGroupCreationForm(forms.ModelForm): |
528 |
kind = forms.ModelChoiceField( |
529 |
queryset=GroupKind.objects.all(), |
530 |
label="",
|
531 |
widget=forms.HiddenInput() |
532 |
) |
533 |
name = forms.URLField() |
534 |
moderation_enabled = forms.BooleanField( |
535 |
help_text="Check if you want to approve members participation manually",
|
536 |
required=False
|
537 |
) |
538 |
max_participants = forms.IntegerField( |
539 |
widget=forms.HiddenInput(), label='', required=False |
540 |
) |
541 |
|
542 |
class Meta: |
543 |
model = AstakosGroup |
544 |
|
545 |
def __init__(self, *args, **kwargs): |
546 |
#update QueryDict
|
547 |
args = list(args)
|
548 |
qd = args.pop(0).copy()
|
549 |
members_unlimited = qd.pop('members_unlimited', False) |
550 |
members_uplimit = qd.pop('members_uplimit', None) |
551 |
max_participants = None if members_unlimited else members_uplimit |
552 |
qd['max_participants']= max_participants.pop(0) if max_participants else None |
553 |
|
554 |
#substitue QueryDict
|
555 |
args.insert(0, qd)
|
556 |
|
557 |
super(AstakosGroupCreationForm, self).__init__(*args, **kwargs) |
558 |
self.fields.keyOrder = ['kind', 'name', 'homepage', 'desc', |
559 |
'issue_date', 'expiration_date', |
560 |
'moderation_enabled', 'max_participants'] |
561 |
|
562 |
def add_field((k, v)): |
563 |
self.fields[k] = forms.IntegerField(
|
564 |
required=False,
|
565 |
widget=forms.HiddenInput() |
566 |
) |
567 |
map(add_field,
|
568 |
((k, v) for k,v in qd.iteritems() if k.endswith('_uplimit')) |
569 |
) |
570 |
|
571 |
def policies(self): |
572 |
for name, uplimit in self.cleaned_data.iteritems(): |
573 |
subs = name.split('_uplimit')
|
574 |
if len(subs) == 2: |
575 |
prefix, suffix = subs |
576 |
# # yield only those having a value
|
577 |
# if not value:
|
578 |
# continue
|
579 |
s, r = prefix.split(RESOURCE_SEPARATOR) |
580 |
yield dict(service=s, resource=r, uplimit=uplimit) |
581 |
|
582 |
|
583 |
class AstakosGroupUpdateForm(forms.ModelForm): |
584 |
class Meta: |
585 |
model = AstakosGroup |
586 |
fields = ('homepage', 'desc') |
587 |
|
588 |
|
589 |
class AddGroupMembersForm(forms.Form): |
590 |
q = forms.CharField( |
591 |
max_length=800, widget=forms.Textarea, label=_('Search users'), |
592 |
help_text=_('Add comma separated user emails'),
|
593 |
required=True)
|
594 |
|
595 |
def clean(self): |
596 |
q = self.cleaned_data.get('q') or '' |
597 |
users = q.split(',')
|
598 |
users = list(u.strip() for u in users if u) |
599 |
db_entries = AstakosUser.objects.filter(email__in=users) |
600 |
unknown = list(set(users) - set(u.email for u in db_entries)) |
601 |
if unknown:
|
602 |
raise forms.ValidationError(
|
603 |
_('Unknown users: %s' % ','.join(unknown))) |
604 |
self.valid_users = db_entries
|
605 |
return self.cleaned_data |
606 |
|
607 |
def get_valid_users(self): |
608 |
"""Should be called after form cleaning"""
|
609 |
try:
|
610 |
return self.valid_users |
611 |
except:
|
612 |
return ()
|
613 |
|
614 |
|
615 |
class AstakosGroupSearchForm(forms.Form): |
616 |
q = forms.CharField(max_length=200, label='Search group') |
617 |
|
618 |
|
619 |
class TimelineForm(forms.Form): |
620 |
# entity = forms.CharField(
|
621 |
# widget=forms.HiddenInput(), label='')
|
622 |
entity = forms.ModelChoiceField( |
623 |
queryset=AstakosUser.objects.filter(is_active=True)
|
624 |
) |
625 |
resource = forms.ModelChoiceField( |
626 |
queryset=Resource.objects.all() |
627 |
) |
628 |
start_date = forms.DateTimeField() |
629 |
end_date = forms.DateTimeField() |
630 |
details = forms.BooleanField(required=False, label="Detailed Listing") |
631 |
operation = forms.ChoiceField( |
632 |
label='Charge Method',
|
633 |
choices=(('', '-------------'), |
634 |
('charge_usage', 'Charge Usage'), |
635 |
('charge_traffic', 'Charge Traffic'), ) |
636 |
) |
637 |
|
638 |
def clean(self): |
639 |
super(TimelineForm, self).clean() |
640 |
d = self.cleaned_data
|
641 |
if 'resource' in d: |
642 |
d['resource'] = str(d['resource']) |
643 |
if 'start_date' in d: |
644 |
d['start_date'] = d['start_date'].strftime( |
645 |
"%Y-%m-%dT%H:%M:%S.%f")[:24] |
646 |
if 'end_date' in d: |
647 |
d['end_date'] = d['end_date'].strftime("%Y-%m-%dT%H:%M:%S.%f")[:24] |
648 |
if 'entity' in d: |
649 |
d['entity'] = d['entity'].email |
650 |
return d
|
651 |
|
652 |
|
653 |
class AstakosGroupSortForm(forms.Form): |
654 |
sort_by = forms.ChoiceField(label='Sort by',
|
655 |
choices=(('groupname', 'Name'), |
656 |
('kindname', 'Type'), |
657 |
('issue_date', 'Issue Date'), |
658 |
('expiration_date',
|
659 |
'Expiration Date'),
|
660 |
('approved_members_num',
|
661 |
'Participants'),
|
662 |
('is_enabled', 'Status'), |
663 |
('moderation_enabled', 'Moderation'), |
664 |
('membership_status',
|
665 |
'Enrollment Status')
|
666 |
), |
667 |
required=False)
|
668 |
|
669 |
|
670 |
class MembersSortForm(forms.Form): |
671 |
sort_by = forms.ChoiceField(label='Sort by',
|
672 |
choices=(('person__email', 'User Id'), |
673 |
('person__first_name', 'Name'), |
674 |
('date_joined', 'Status') |
675 |
), |
676 |
required=False)
|
677 |
|
678 |
|
679 |
class PickResourceForm(forms.Form): |
680 |
resource = forms.ModelChoiceField( |
681 |
queryset=Resource.objects.select_related().all() |
682 |
) |
683 |
resource.widget.attrs["onchange"] = "this.form.submit()" |
684 |
|
685 |
|
686 |
class ExtendedSetPasswordForm(SetPasswordForm): |
687 |
"""
|
688 |
Extends SetPasswordForm by enabling user
|
689 |
to optionally renew also the token.
|
690 |
"""
|
691 |
if not NEWPASSWD_INVALIDATE_TOKEN: |
692 |
renew = forms.BooleanField(label='Renew token', required=False, |
693 |
initial=True,
|
694 |
help_text='Unsetting this may result in security risk.')
|
695 |
|
696 |
def __init__(self, user, *args, **kwargs): |
697 |
super(ExtendedSetPasswordForm, self).__init__(user, *args, **kwargs) |
698 |
|
699 |
def save(self, commit=True): |
700 |
if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'): |
701 |
if isinstance(self.user, AstakosUser): |
702 |
self.user.renew_token()
|
703 |
return super(ExtendedSetPasswordForm, self).save(commit=commit) |