root / snf-astakos-app / astakos / im / forms.py @ a9c0cd9f
History | View | Annotate | Download (31.6 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.conf import settings |
48 |
from django.forms.models import fields_for_model |
49 |
from django.db import transaction |
50 |
|
51 |
from astakos.im.models import ( |
52 |
AstakosUser, EmailChange, AstakosGroup, Invitation, GroupKind, |
53 |
Resource, PendingThirdPartyUser, get_latest_terms, RESOURCE_SEPARATOR |
54 |
) |
55 |
from astakos.im.settings import ( |
56 |
INVITATIONS_PER_LEVEL, BASEURL, SITENAME, RECAPTCHA_PRIVATE_KEY, |
57 |
RECAPTCHA_ENABLED, DEFAULT_CONTACT_EMAIL, LOGGING_LEVEL, |
58 |
PASSWORD_RESET_EMAIL_SUBJECT, NEWPASSWD_INVALIDATE_TOKEN, |
59 |
MODERATION_ENABLED |
60 |
) |
61 |
from astakos.im.widgets import DummyWidget, RecaptchaWidget |
62 |
from astakos.im.functions import send_change_email |
63 |
|
64 |
from astakos.im.util import reserved_email, get_query |
65 |
|
66 |
import astakos.im.messages as astakos_messages |
67 |
|
68 |
import logging |
69 |
import hashlib |
70 |
import recaptcha.client.captcha as captcha |
71 |
from random import random |
72 |
|
73 |
logger = logging.getLogger(__name__) |
74 |
|
75 |
class StoreUserMixin(object): |
76 |
|
77 |
@transaction.commit_on_success
|
78 |
def store_user(self, user, request): |
79 |
user.save() |
80 |
self.post_store_user(user, request)
|
81 |
return user
|
82 |
|
83 |
def post_store_user(self, user, request): |
84 |
"""
|
85 |
Interface method for descendant backends to be able to do stuff within
|
86 |
the transaction enabled by store_user.
|
87 |
"""
|
88 |
pass
|
89 |
|
90 |
|
91 |
class LocalUserCreationForm(UserCreationForm, StoreUserMixin): |
92 |
"""
|
93 |
Extends the built in UserCreationForm in several ways:
|
94 |
|
95 |
* Adds email, first_name, last_name, recaptcha_challenge_field, recaptcha_response_field field.
|
96 |
* The username field isn't visible and it is assigned a generated id.
|
97 |
* User created is not active.
|
98 |
"""
|
99 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
100 |
recaptcha_response_field = forms.CharField( |
101 |
widget=RecaptchaWidget, label='')
|
102 |
|
103 |
class Meta: |
104 |
model = AstakosUser |
105 |
fields = ("email", "first_name", "last_name", |
106 |
"has_signed_terms", "has_signed_terms") |
107 |
|
108 |
def __init__(self, *args, **kwargs): |
109 |
"""
|
110 |
Changes the order of fields, and removes the username field.
|
111 |
"""
|
112 |
request = kwargs.pop('request', None) |
113 |
if request:
|
114 |
self.ip = request.META.get('REMOTE_ADDR', |
115 |
request.META.get('HTTP_X_REAL_IP', None)) |
116 |
|
117 |
super(LocalUserCreationForm, self).__init__(*args, **kwargs) |
118 |
self.fields.keyOrder = ['email', 'first_name', 'last_name', |
119 |
'password1', 'password2'] |
120 |
|
121 |
if RECAPTCHA_ENABLED:
|
122 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
123 |
'recaptcha_response_field', ])
|
124 |
if get_latest_terms():
|
125 |
self.fields.keyOrder.append('has_signed_terms') |
126 |
|
127 |
if 'has_signed_terms' in self.fields: |
128 |
# Overriding field label since we need to apply a link
|
129 |
# to the terms within the label
|
130 |
terms_link_html = '<a href="%s" target="_blank">%s</a>' \
|
131 |
% (reverse('latest_terms'), _("the terms")) |
132 |
self.fields['has_signed_terms'].label = \ |
133 |
mark_safe("I agree with %s" % terms_link_html)
|
134 |
|
135 |
def clean_email(self): |
136 |
email = self.cleaned_data['email'].lower() |
137 |
if not email: |
138 |
raise forms.ValidationError(_(astakos_messages.REQUIRED_FIELD))
|
139 |
if reserved_email(email):
|
140 |
raise forms.ValidationError(_(astakos_messages.EMAIL_USED))
|
141 |
return email
|
142 |
|
143 |
def clean_has_signed_terms(self): |
144 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
145 |
if not has_signed_terms: |
146 |
raise forms.ValidationError(_(astakos_messages.SIGN_TERMS))
|
147 |
return has_signed_terms
|
148 |
|
149 |
def clean_recaptcha_response_field(self): |
150 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
151 |
self.validate_captcha()
|
152 |
return self.cleaned_data['recaptcha_response_field'] |
153 |
|
154 |
def clean_recaptcha_challenge_field(self): |
155 |
if 'recaptcha_response_field' in self.cleaned_data: |
156 |
self.validate_captcha()
|
157 |
return self.cleaned_data['recaptcha_challenge_field'] |
158 |
|
159 |
def validate_captcha(self): |
160 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
161 |
rrf = self.cleaned_data['recaptcha_response_field'] |
162 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
163 |
if not check.is_valid: |
164 |
raise forms.ValidationError(_(astakos_messages.CAPTCHA_VALIDATION_ERR))
|
165 |
|
166 |
def post_store_user(self, user, request): |
167 |
"""
|
168 |
Interface method for descendant backends to be able to do stuff within
|
169 |
the transaction enabled by store_user.
|
170 |
"""
|
171 |
user.add_auth_provider('local', auth_backend='astakos') |
172 |
user.set_password(self.cleaned_data['password1']) |
173 |
|
174 |
def save(self, commit=True): |
175 |
"""
|
176 |
Saves the email, first_name and last_name properties, after the normal
|
177 |
save behavior is complete.
|
178 |
"""
|
179 |
user = super(LocalUserCreationForm, self).save(commit=False) |
180 |
user.renew_token() |
181 |
if commit:
|
182 |
user.save() |
183 |
logger.log(LOGGING_LEVEL, 'Created user %s' % user.email)
|
184 |
return user
|
185 |
|
186 |
|
187 |
class InvitedLocalUserCreationForm(LocalUserCreationForm): |
188 |
"""
|
189 |
Extends the LocalUserCreationForm: email is readonly.
|
190 |
"""
|
191 |
class Meta: |
192 |
model = AstakosUser |
193 |
fields = ("email", "first_name", "last_name", "has_signed_terms") |
194 |
|
195 |
def __init__(self, *args, **kwargs): |
196 |
"""
|
197 |
Changes the order of fields, and removes the username field.
|
198 |
"""
|
199 |
super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs) |
200 |
|
201 |
#set readonly form fields
|
202 |
ro = ('email', 'username',) |
203 |
for f in ro: |
204 |
self.fields[f].widget.attrs['readonly'] = True |
205 |
|
206 |
def save(self, commit=True): |
207 |
user = super(InvitedLocalUserCreationForm, self).save(commit=False) |
208 |
user.update_invitations_level() |
209 |
user.email_verified = True
|
210 |
if commit:
|
211 |
user.save() |
212 |
return user
|
213 |
|
214 |
|
215 |
class ThirdPartyUserCreationForm(forms.ModelForm, StoreUserMixin): |
216 |
id = forms.CharField( |
217 |
widget=forms.HiddenInput(), |
218 |
label='',
|
219 |
required=False
|
220 |
) |
221 |
third_party_identifier = forms.CharField( |
222 |
widget=forms.HiddenInput(), |
223 |
label=''
|
224 |
) |
225 |
class Meta: |
226 |
model = AstakosUser |
227 |
fields = ['id', 'email', 'third_party_identifier', 'first_name', 'last_name'] |
228 |
|
229 |
def __init__(self, *args, **kwargs): |
230 |
"""
|
231 |
Changes the order of fields, and removes the username field.
|
232 |
"""
|
233 |
self.request = kwargs.get('request', None) |
234 |
if self.request: |
235 |
kwargs.pop('request')
|
236 |
|
237 |
latest_terms = get_latest_terms() |
238 |
if latest_terms:
|
239 |
self._meta.fields.append('has_signed_terms') |
240 |
|
241 |
super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs) |
242 |
|
243 |
if latest_terms:
|
244 |
self.fields.keyOrder.append('has_signed_terms') |
245 |
|
246 |
if 'has_signed_terms' in self.fields: |
247 |
# Overriding field label since we need to apply a link
|
248 |
# to the terms within the label
|
249 |
terms_link_html = '<a href="%s" target="_blank">%s</a>' \
|
250 |
% (reverse('latest_terms'), _("the terms")) |
251 |
self.fields['has_signed_terms'].label = \ |
252 |
mark_safe("I agree with %s" % terms_link_html)
|
253 |
|
254 |
def clean_email(self): |
255 |
email = self.cleaned_data['email'].lower() |
256 |
if not email: |
257 |
raise forms.ValidationError(_(astakos_messages.REQUIRED_FIELD))
|
258 |
return email
|
259 |
|
260 |
def clean_has_signed_terms(self): |
261 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
262 |
if not has_signed_terms: |
263 |
raise forms.ValidationError(_(astakos_messages.SIGN_TERMS))
|
264 |
return has_signed_terms
|
265 |
|
266 |
def post_store_user(self, user, request): |
267 |
pending = PendingThirdPartyUser.objects.get( |
268 |
token=request.POST.get('third_party_token'),
|
269 |
third_party_identifier= \ |
270 |
self.cleaned_data.get('third_party_identifier')) |
271 |
return user.add_pending_auth_provider(pending)
|
272 |
|
273 |
|
274 |
def save(self, commit=True): |
275 |
user = super(ThirdPartyUserCreationForm, self).save(commit=False) |
276 |
user.set_unusable_password() |
277 |
user.renew_token() |
278 |
if commit:
|
279 |
user.save() |
280 |
logger.log(LOGGING_LEVEL, 'Created user %s' % user.email)
|
281 |
return user
|
282 |
|
283 |
|
284 |
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm): |
285 |
"""
|
286 |
Extends the ThirdPartyUserCreationForm: email is readonly.
|
287 |
"""
|
288 |
def __init__(self, *args, **kwargs): |
289 |
"""
|
290 |
Changes the order of fields, and removes the username field.
|
291 |
"""
|
292 |
super(
|
293 |
InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
|
294 |
|
295 |
#set readonly form fields
|
296 |
ro = ('email',)
|
297 |
for f in ro: |
298 |
self.fields[f].widget.attrs['readonly'] = True |
299 |
|
300 |
def save(self, commit=True): |
301 |
user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False) |
302 |
user.set_invitation_level() |
303 |
user.email_verified = True
|
304 |
if commit:
|
305 |
user.save() |
306 |
return user
|
307 |
|
308 |
|
309 |
class ShibbolethUserCreationForm(ThirdPartyUserCreationForm): |
310 |
additional_email = forms.CharField( |
311 |
widget=forms.HiddenInput(), label='', required=False) |
312 |
|
313 |
def __init__(self, *args, **kwargs): |
314 |
super(ShibbolethUserCreationForm, self).__init__(*args, **kwargs) |
315 |
# copy email value to additional_mail in case user will change it
|
316 |
name = 'email'
|
317 |
field = self.fields[name]
|
318 |
self.initial['additional_email'] = self.initial.get(name, field.initial) |
319 |
self.initial['email'] = None |
320 |
|
321 |
def clean_email(self): |
322 |
email = self.cleaned_data['email'].lower() |
323 |
if self.instance: |
324 |
if self.instance.email == email: |
325 |
raise forms.ValidationError(_("This is your current email.")) |
326 |
for user in AstakosUser.objects.filter(email__iexact=email): |
327 |
if user.provider == 'shibboleth': |
328 |
raise forms.ValidationError(_(
|
329 |
"This email is already associated with another \
|
330 |
shibboleth account."
|
331 |
) |
332 |
) |
333 |
else:
|
334 |
raise forms.ValidationError(_("This email is already used")) |
335 |
super(ShibbolethUserCreationForm, self).clean_email() |
336 |
return email
|
337 |
|
338 |
|
339 |
class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, |
340 |
InvitedThirdPartyUserCreationForm): |
341 |
pass
|
342 |
|
343 |
|
344 |
class LoginForm(AuthenticationForm): |
345 |
username = forms.EmailField(label=_("Email"))
|
346 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
347 |
recaptcha_response_field = forms.CharField( |
348 |
widget=RecaptchaWidget, label='')
|
349 |
|
350 |
def __init__(self, *args, **kwargs): |
351 |
was_limited = kwargs.get('was_limited', False) |
352 |
request = kwargs.get('request', None) |
353 |
if request:
|
354 |
self.ip = request.META.get('REMOTE_ADDR', |
355 |
request.META.get('HTTP_X_REAL_IP', None)) |
356 |
|
357 |
t = ('request', 'was_limited') |
358 |
for elem in t: |
359 |
if elem in kwargs.keys(): |
360 |
kwargs.pop(elem) |
361 |
super(LoginForm, self).__init__(*args, **kwargs) |
362 |
|
363 |
self.fields.keyOrder = ['username', 'password'] |
364 |
if was_limited and RECAPTCHA_ENABLED: |
365 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
366 |
'recaptcha_response_field', ])
|
367 |
|
368 |
def clean_username(self): |
369 |
if 'username' in self.cleaned_data: |
370 |
return self.cleaned_data['username'].lower() |
371 |
|
372 |
def clean_recaptcha_response_field(self): |
373 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
374 |
self.validate_captcha()
|
375 |
return self.cleaned_data['recaptcha_response_field'] |
376 |
|
377 |
def clean_recaptcha_challenge_field(self): |
378 |
if 'recaptcha_response_field' in self.cleaned_data: |
379 |
self.validate_captcha()
|
380 |
return self.cleaned_data['recaptcha_challenge_field'] |
381 |
|
382 |
def validate_captcha(self): |
383 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
384 |
rrf = self.cleaned_data['recaptcha_response_field'] |
385 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
386 |
if not check.is_valid: |
387 |
raise forms.ValidationError(_(astakos_messages.CAPTCHA_VALIDATION_ERR))
|
388 |
|
389 |
def clean(self): |
390 |
"""
|
391 |
Override default behavior in order to check user's activation later
|
392 |
"""
|
393 |
try:
|
394 |
super(LoginForm, self).clean() |
395 |
except forms.ValidationError, e:
|
396 |
if self.user_cache is None: |
397 |
raise
|
398 |
if self.request: |
399 |
if not self.request.session.test_cookie_worked(): |
400 |
raise
|
401 |
return self.cleaned_data |
402 |
|
403 |
|
404 |
class ProfileForm(forms.ModelForm): |
405 |
"""
|
406 |
Subclass of ``ModelForm`` for permiting user to edit his/her profile.
|
407 |
Most of the fields are readonly since the user is not allowed to change
|
408 |
them.
|
409 |
|
410 |
The class defines a save method which sets ``is_verified`` to True so as the
|
411 |
user during the next login will not to be redirected to profile page.
|
412 |
"""
|
413 |
renew = forms.BooleanField(label='Renew token', required=False) |
414 |
|
415 |
class Meta: |
416 |
model = AstakosUser |
417 |
fields = ('email', 'first_name', 'last_name', 'auth_token', |
418 |
'auth_token_expires')
|
419 |
|
420 |
def __init__(self, *args, **kwargs): |
421 |
self.session_key = kwargs.pop('session_key', None) |
422 |
super(ProfileForm, self).__init__(*args, **kwargs) |
423 |
instance = getattr(self, 'instance', None) |
424 |
ro_fields = ('email', 'auth_token', 'auth_token_expires') |
425 |
if instance and instance.id: |
426 |
for field in ro_fields: |
427 |
self.fields[field].widget.attrs['readonly'] = True |
428 |
|
429 |
def save(self, commit=True): |
430 |
user = super(ProfileForm, self).save(commit=False) |
431 |
user.is_verified = True
|
432 |
if self.cleaned_data.get('renew'): |
433 |
user.renew_token( |
434 |
flush_sessions=True,
|
435 |
current_key=self.session_key
|
436 |
) |
437 |
if commit:
|
438 |
user.save() |
439 |
return user
|
440 |
|
441 |
|
442 |
class FeedbackForm(forms.Form): |
443 |
"""
|
444 |
Form for writing feedback.
|
445 |
"""
|
446 |
feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
|
447 |
feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
|
448 |
required=False)
|
449 |
|
450 |
|
451 |
class SendInvitationForm(forms.Form): |
452 |
"""
|
453 |
Form for sending an invitations
|
454 |
"""
|
455 |
|
456 |
email = forms.EmailField(required=True, label='Email address') |
457 |
first_name = forms.EmailField(label='First name')
|
458 |
last_name = forms.EmailField(label='Last name')
|
459 |
|
460 |
|
461 |
class ExtendedPasswordResetForm(PasswordResetForm): |
462 |
"""
|
463 |
Extends PasswordResetForm by overriding save method:
|
464 |
passes a custom from_email in send_mail.
|
465 |
|
466 |
Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
|
467 |
accepts a from_email argument.
|
468 |
"""
|
469 |
def clean_email(self): |
470 |
email = super(ExtendedPasswordResetForm, self).clean_email() |
471 |
try:
|
472 |
user = AstakosUser.objects.get(email__iexact=email, is_active=True)
|
473 |
if not user.has_usable_password(): |
474 |
raise forms.ValidationError(_(astakos_messages.UNUSABLE_PASSWORD))
|
475 |
|
476 |
if not user.can_change_password(): |
477 |
raise forms.ValidationError(_('Password change for this account' |
478 |
' is not supported.'))
|
479 |
|
480 |
except AstakosUser.DoesNotExist, e:
|
481 |
raise forms.ValidationError(_(astakos_messages.EMAIL_UNKNOWN))
|
482 |
return email
|
483 |
|
484 |
def save( |
485 |
self, domain_override=None, email_template_name='registration/password_reset_email.html', |
486 |
use_https=False, token_generator=default_token_generator, request=None): |
487 |
"""
|
488 |
Generates a one-use only link for resetting password and sends to the user.
|
489 |
"""
|
490 |
for user in self.users_cache: |
491 |
url = user.astakosuser.get_password_reset_url(token_generator) |
492 |
url = urljoin(BASEURL, url) |
493 |
t = loader.get_template(email_template_name) |
494 |
c = { |
495 |
'email': user.email,
|
496 |
'url': url,
|
497 |
'site_name': SITENAME,
|
498 |
'user': user,
|
499 |
'baseurl': BASEURL,
|
500 |
'support': DEFAULT_CONTACT_EMAIL
|
501 |
} |
502 |
from_email = settings.SERVER_EMAIL |
503 |
send_mail(_(PASSWORD_RESET_EMAIL_SUBJECT), |
504 |
t.render(Context(c)), from_email, [user.email]) |
505 |
|
506 |
|
507 |
class EmailChangeForm(forms.ModelForm): |
508 |
class Meta: |
509 |
model = EmailChange |
510 |
fields = ('new_email_address',)
|
511 |
|
512 |
def clean_new_email_address(self): |
513 |
addr = self.cleaned_data['new_email_address'] |
514 |
if AstakosUser.objects.filter(email__iexact=addr):
|
515 |
raise forms.ValidationError(_(astakos_messages.EMAIL_USED))
|
516 |
return addr
|
517 |
|
518 |
def save(self, email_template_name, request, commit=True): |
519 |
ec = super(EmailChangeForm, self).save(commit=False) |
520 |
ec.user = request.user |
521 |
activation_key = hashlib.sha1( |
522 |
str(random()) + smart_str(ec.new_email_address))
|
523 |
ec.activation_key = activation_key.hexdigest() |
524 |
if commit:
|
525 |
ec.save() |
526 |
send_change_email(ec, request, email_template_name=email_template_name) |
527 |
|
528 |
|
529 |
class SignApprovalTermsForm(forms.ModelForm): |
530 |
class Meta: |
531 |
model = AstakosUser |
532 |
fields = ("has_signed_terms",)
|
533 |
|
534 |
def __init__(self, *args, **kwargs): |
535 |
super(SignApprovalTermsForm, self).__init__(*args, **kwargs) |
536 |
|
537 |
def clean_has_signed_terms(self): |
538 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
539 |
if not has_signed_terms: |
540 |
raise forms.ValidationError(_(astakos_messages.SIGN_TERMS))
|
541 |
return has_signed_terms
|
542 |
|
543 |
|
544 |
class InvitationForm(forms.ModelForm): |
545 |
username = forms.EmailField(label=_("Email"))
|
546 |
|
547 |
def __init__(self, *args, **kwargs): |
548 |
super(InvitationForm, self).__init__(*args, **kwargs) |
549 |
|
550 |
class Meta: |
551 |
model = Invitation |
552 |
fields = ('username', 'realname') |
553 |
|
554 |
def clean_username(self): |
555 |
username = self.cleaned_data['username'] |
556 |
try:
|
557 |
Invitation.objects.get(username=username) |
558 |
raise forms.ValidationError(_(astakos_messages.INVITATION_EMAIL_EXISTS))
|
559 |
except Invitation.DoesNotExist:
|
560 |
pass
|
561 |
return username
|
562 |
|
563 |
|
564 |
class ExtendedPasswordChangeForm(PasswordChangeForm): |
565 |
"""
|
566 |
Extends PasswordChangeForm by enabling user
|
567 |
to optionally renew also the token.
|
568 |
"""
|
569 |
if not NEWPASSWD_INVALIDATE_TOKEN: |
570 |
renew = forms.BooleanField(label='Renew token', required=False, |
571 |
initial=True,
|
572 |
help_text='Unsetting this may result in security risk.')
|
573 |
|
574 |
def __init__(self, user, *args, **kwargs): |
575 |
self.session_key = kwargs.pop('session_key', None) |
576 |
super(ExtendedPasswordChangeForm, self).__init__(user, *args, **kwargs) |
577 |
|
578 |
def save(self, commit=True): |
579 |
try:
|
580 |
if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'): |
581 |
self.user.renew_token()
|
582 |
self.user.flush_sessions(current_key=self.session_key) |
583 |
except AttributeError: |
584 |
# if user model does has not such methods
|
585 |
pass
|
586 |
return super(ExtendedPasswordChangeForm, self).save(commit=commit) |
587 |
|
588 |
|
589 |
class AstakosGroupCreationForm(forms.ModelForm): |
590 |
kind = forms.ModelChoiceField( |
591 |
queryset=GroupKind.objects.all(), |
592 |
label="",
|
593 |
widget=forms.HiddenInput() |
594 |
) |
595 |
name = forms.URLField(widget=forms.TextInput(attrs={'placeholder': 'eg. foo.ece.ntua.gr'}), help_text="Name should be in the form of dns",) |
596 |
moderation_enabled = forms.BooleanField( |
597 |
help_text="Check if you want to approve members participation manually",
|
598 |
required=False,
|
599 |
initial=True
|
600 |
) |
601 |
max_participants = forms.IntegerField( |
602 |
required=True, min_value=1 |
603 |
) |
604 |
|
605 |
class Meta: |
606 |
model = AstakosGroup |
607 |
|
608 |
def __init__(self, *args, **kwargs): |
609 |
#update QueryDict
|
610 |
args = list(args)
|
611 |
qd = args.pop(0).copy()
|
612 |
members_unlimited = qd.pop('members_unlimited', False) |
613 |
members_uplimit = qd.pop('members_uplimit', None) |
614 |
# max_participants = None if members_unlimited else members_uplimit
|
615 |
# qd['max_participants']= max_participants.pop(0) if max_participants else None
|
616 |
|
617 |
#substitue QueryDict
|
618 |
args.insert(0, qd)
|
619 |
|
620 |
super(AstakosGroupCreationForm, self).__init__(*args, **kwargs) |
621 |
self.fields.keyOrder = ['kind', 'name', 'homepage', 'desc', |
622 |
'issue_date', 'expiration_date', |
623 |
'moderation_enabled', 'max_participants'] |
624 |
def add_fields((k, v)): |
625 |
k = k.partition('_proxy')[0] |
626 |
self.fields[k] = forms.IntegerField(
|
627 |
required=False,
|
628 |
widget=forms.HiddenInput(), |
629 |
min_value=1
|
630 |
) |
631 |
map(add_fields,
|
632 |
((k, v) for k,v in qd.iteritems() if k.endswith('_uplimit')) |
633 |
) |
634 |
|
635 |
def add_fields((k, v)): |
636 |
self.fields[k] = forms.BooleanField(
|
637 |
required=False,
|
638 |
#widget=forms.HiddenInput()
|
639 |
) |
640 |
map(add_fields,
|
641 |
((k, v) for k,v in qd.iteritems() if k.startswith('is_selected_')) |
642 |
) |
643 |
|
644 |
def policies(self): |
645 |
self.clean()
|
646 |
policies = [] |
647 |
append = policies.append |
648 |
for name, uplimit in self.cleaned_data.iteritems(): |
649 |
|
650 |
subs = name.split('_uplimit')
|
651 |
if len(subs) == 2: |
652 |
prefix, suffix = subs |
653 |
s, sep, r = prefix.partition(RESOURCE_SEPARATOR) |
654 |
resource = Resource.objects.get(service__name=s, name=r) |
655 |
|
656 |
# keep only resource limits for selected resource groups
|
657 |
if self.cleaned_data.get( |
658 |
'is_selected_%s' % resource.group, False |
659 |
): |
660 |
append(dict(service=s, resource=r, uplimit=uplimit))
|
661 |
return policies
|
662 |
|
663 |
class AstakosGroupCreationSummaryForm(forms.ModelForm): |
664 |
kind = forms.ModelChoiceField( |
665 |
queryset=GroupKind.objects.all(), |
666 |
label="",
|
667 |
widget=forms.HiddenInput() |
668 |
) |
669 |
name = forms.URLField() |
670 |
moderation_enabled = forms.BooleanField( |
671 |
help_text="Check if you want to approve members participation manually",
|
672 |
required=False,
|
673 |
initial=True
|
674 |
) |
675 |
max_participants = forms.IntegerField( |
676 |
required=False, min_value=1 |
677 |
) |
678 |
|
679 |
class Meta: |
680 |
model = AstakosGroup |
681 |
|
682 |
def __init__(self, *args, **kwargs): |
683 |
#update QueryDict
|
684 |
args = list(args)
|
685 |
qd = args.pop(0).copy()
|
686 |
members_unlimited = qd.pop('members_unlimited', False) |
687 |
members_uplimit = qd.pop('members_uplimit', None) |
688 |
# max_participants = None if members_unlimited else members_uplimit
|
689 |
# qd['max_participants']= max_participants.pop(0) if max_participants else None
|
690 |
|
691 |
#substitue QueryDict
|
692 |
args.insert(0, qd)
|
693 |
|
694 |
super(AstakosGroupCreationSummaryForm, self).__init__(*args, **kwargs) |
695 |
self.fields.keyOrder = ['kind', 'name', 'homepage', 'desc', |
696 |
'issue_date', 'expiration_date', |
697 |
'moderation_enabled', 'max_participants'] |
698 |
def add_fields((k, v)): |
699 |
self.fields[k] = forms.IntegerField(
|
700 |
required=False,
|
701 |
widget=forms.TextInput(), |
702 |
min_value=1
|
703 |
) |
704 |
map(add_fields,
|
705 |
((k, v) for k,v in qd.iteritems() if k.endswith('_uplimit')) |
706 |
) |
707 |
|
708 |
def add_fields((k, v)): |
709 |
self.fields[k] = forms.BooleanField(
|
710 |
required=False,
|
711 |
widget=forms.HiddenInput() |
712 |
) |
713 |
map(add_fields,
|
714 |
((k, v) for k,v in qd.iteritems() if k.startswith('is_selected_')) |
715 |
) |
716 |
for f in self.fields.values(): |
717 |
f.widget = forms.HiddenInput() |
718 |
|
719 |
def clean(self): |
720 |
super(AstakosGroupCreationSummaryForm, self).clean() |
721 |
self.cleaned_data['policies'] = [] |
722 |
append = self.cleaned_data['policies'].append |
723 |
#tbd = [f for f in self.fields if (f.startswith('is_selected_') and (not f.endswith('_proxy')))]
|
724 |
tbd = [f for f in self.fields if f.startswith('is_selected_')] |
725 |
for name, uplimit in self.cleaned_data.iteritems(): |
726 |
subs = name.split('_uplimit')
|
727 |
if len(subs) == 2: |
728 |
tbd.append(name) |
729 |
prefix, suffix = subs |
730 |
s, sep, r = prefix.partition(RESOURCE_SEPARATOR) |
731 |
resource = Resource.objects.get(service__name=s, name=r) |
732 |
|
733 |
# keep only resource limits for selected resource groups
|
734 |
if self.cleaned_data.get( |
735 |
'is_selected_%s' % resource.group, False |
736 |
): |
737 |
append(dict(service=s, resource=r, uplimit=uplimit))
|
738 |
for name in tbd: |
739 |
self.cleaned_data.pop(name, None) |
740 |
return self.cleaned_data |
741 |
|
742 |
class AstakosGroupUpdateForm(forms.ModelForm): |
743 |
class Meta: |
744 |
model = AstakosGroup |
745 |
fields = ( 'desc','homepage') |
746 |
|
747 |
|
748 |
class AddGroupMembersForm(forms.Form): |
749 |
q = forms.CharField( |
750 |
max_length=800, widget=forms.Textarea, label=_('Add members'), |
751 |
help_text=_(astakos_messages.ADD_GROUP_MEMBERS_Q_HELP), |
752 |
required=True)
|
753 |
|
754 |
def clean(self): |
755 |
q = self.cleaned_data.get('q') or '' |
756 |
users = q.split(',')
|
757 |
users = list(u.strip() for u in users if u) |
758 |
db_entries = AstakosUser.objects.filter(email__in=users) |
759 |
unknown = list(set(users) - set(u.email for u in db_entries)) |
760 |
if unknown:
|
761 |
raise forms.ValidationError(_(astakos_messages.UNKNOWN_USERS) % ','.join(unknown)) |
762 |
self.valid_users = db_entries
|
763 |
return self.cleaned_data |
764 |
|
765 |
def get_valid_users(self): |
766 |
"""Should be called after form cleaning"""
|
767 |
try:
|
768 |
return self.valid_users |
769 |
except:
|
770 |
return ()
|
771 |
|
772 |
|
773 |
class AstakosGroupSearchForm(forms.Form): |
774 |
q = forms.CharField(max_length=200, label='Search project') |
775 |
|
776 |
|
777 |
class TimelineForm(forms.Form): |
778 |
entity = forms.ModelChoiceField( |
779 |
queryset=AstakosUser.objects.filter(is_active=True)
|
780 |
) |
781 |
resource = forms.ModelChoiceField( |
782 |
queryset=Resource.objects.all() |
783 |
) |
784 |
start_date = forms.DateTimeField() |
785 |
end_date = forms.DateTimeField() |
786 |
details = forms.BooleanField(required=False, label="Detailed Listing") |
787 |
operation = forms.ChoiceField( |
788 |
label='Charge Method',
|
789 |
choices=(('', '-------------'), |
790 |
('charge_usage', 'Charge Usage'), |
791 |
('charge_traffic', 'Charge Traffic'), ) |
792 |
) |
793 |
|
794 |
def clean(self): |
795 |
super(TimelineForm, self).clean() |
796 |
d = self.cleaned_data
|
797 |
if 'resource' in d: |
798 |
d['resource'] = str(d['resource']) |
799 |
if 'start_date' in d: |
800 |
d['start_date'] = d['start_date'].strftime( |
801 |
"%Y-%m-%dT%H:%M:%S.%f")[:24] |
802 |
if 'end_date' in d: |
803 |
d['end_date'] = d['end_date'].strftime("%Y-%m-%dT%H:%M:%S.%f")[:24] |
804 |
if 'entity' in d: |
805 |
d['entity'] = d['entity'].email |
806 |
return d
|
807 |
|
808 |
|
809 |
class AstakosGroupSortForm(forms.Form): |
810 |
sort_by = forms.ChoiceField(label='Sort by',
|
811 |
choices=(('groupname', 'Name'), |
812 |
('kindname', 'Type'), |
813 |
('issue_date', 'Issue Date'), |
814 |
('expiration_date',
|
815 |
'Expiration Date'),
|
816 |
('approved_members_num',
|
817 |
'Participants'),
|
818 |
('is_enabled', 'Status'), |
819 |
('moderation_enabled', 'Moderation'), |
820 |
('membership_status',
|
821 |
'Enrollment Status')
|
822 |
), |
823 |
required=False)
|
824 |
|
825 |
|
826 |
class MembersSortForm(forms.Form): |
827 |
sort_by = forms.ChoiceField(label='Sort by',
|
828 |
choices=(('person__email', 'User Id'), |
829 |
('person__first_name', 'Name'), |
830 |
('date_joined', 'Status') |
831 |
), |
832 |
required=False)
|
833 |
|
834 |
|
835 |
class PickResourceForm(forms.Form): |
836 |
resource = forms.ModelChoiceField( |
837 |
queryset=Resource.objects.select_related().all() |
838 |
) |
839 |
resource.widget.attrs["onchange"] = "this.form.submit()" |
840 |
|
841 |
|
842 |
class ExtendedSetPasswordForm(SetPasswordForm): |
843 |
"""
|
844 |
Extends SetPasswordForm by enabling user
|
845 |
to optionally renew also the token.
|
846 |
"""
|
847 |
if not NEWPASSWD_INVALIDATE_TOKEN: |
848 |
renew = forms.BooleanField( |
849 |
label='Renew token',
|
850 |
required=False,
|
851 |
initial=True,
|
852 |
help_text='Unsetting this may result in security risk.'
|
853 |
) |
854 |
|
855 |
def __init__(self, user, *args, **kwargs): |
856 |
super(ExtendedSetPasswordForm, self).__init__(user, *args, **kwargs) |
857 |
|
858 |
@transaction.commit_on_success()
|
859 |
def save(self, commit=True): |
860 |
try:
|
861 |
self.user = AstakosUser.objects.get(id=self.user.id) |
862 |
if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'): |
863 |
self.user.renew_token()
|
864 |
#self.user.flush_sessions()
|
865 |
if not self.user.has_auth_provider('local'): |
866 |
self.user.add_auth_provider('local', auth_backend='astakos') |
867 |
|
868 |
except BaseException, e: |
869 |
logger.exception(e) |
870 |
return super(ExtendedSetPasswordForm, self).save(commit=commit) |