root / snf-astakos-app / astakos / im / forms.py @ 861458fd
History | View | Annotate | Download (38.5 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 |
from datetime import datetime, timedelta |
36 |
|
37 |
from django import forms |
38 |
from django.utils.translation import ugettext as _ |
39 |
from django.contrib.auth.forms import ( |
40 |
UserCreationForm, AuthenticationForm, |
41 |
PasswordResetForm, PasswordChangeForm, |
42 |
SetPasswordForm) |
43 |
from django.core.mail import send_mail, get_connection |
44 |
from django.contrib.auth.tokens import default_token_generator |
45 |
from django.template import Context, loader |
46 |
from django.utils.http import int_to_base36 |
47 |
from django.core.urlresolvers import reverse |
48 |
from django.utils.safestring import mark_safe |
49 |
from django.utils.encoding import smart_str |
50 |
from django.conf import settings |
51 |
from django.forms.models import fields_for_model |
52 |
from django.db import transaction |
53 |
from django.utils.encoding import smart_unicode |
54 |
from django.core import validators |
55 |
from django.contrib.auth.models import AnonymousUser |
56 |
from django.core.exceptions import PermissionDenied |
57 |
|
58 |
from astakos.im.models import ( |
59 |
AstakosUser, EmailChange, Invitation, |
60 |
Resource, PendingThirdPartyUser, get_latest_terms, RESOURCE_SEPARATOR, |
61 |
ProjectApplication, Project) |
62 |
from astakos.im.settings import ( |
63 |
INVITATIONS_PER_LEVEL, BASEURL, SITENAME, RECAPTCHA_PRIVATE_KEY, |
64 |
RECAPTCHA_ENABLED, DEFAULT_CONTACT_EMAIL, LOGGING_LEVEL, |
65 |
PASSWORD_RESET_EMAIL_SUBJECT, NEWPASSWD_INVALIDATE_TOKEN, |
66 |
MODERATION_ENABLED, PROJECT_MEMBER_JOIN_POLICIES, |
67 |
PROJECT_MEMBER_LEAVE_POLICIES, EMAILCHANGE_ENABLED) |
68 |
from astakos.im.widgets import DummyWidget, RecaptchaWidget |
69 |
from astakos.im.functions import ( |
70 |
send_change_email, submit_application, accept_membership_checks) |
71 |
|
72 |
from astakos.im.util import reserved_email, reserved_verified_email, \ |
73 |
get_query, model_to_dict |
74 |
from astakos.im import auth_providers |
75 |
|
76 |
import astakos.im.messages as astakos_messages |
77 |
|
78 |
import logging |
79 |
import hashlib |
80 |
import recaptcha.client.captcha as captcha |
81 |
import re |
82 |
|
83 |
logger = logging.getLogger(__name__) |
84 |
|
85 |
DOMAIN_VALUE_REGEX = re.compile( |
86 |
r'^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$',
|
87 |
re.IGNORECASE) |
88 |
|
89 |
class StoreUserMixin(object): |
90 |
|
91 |
def store_user(self, user, request): |
92 |
"""
|
93 |
WARNING: this should be wrapped inside a transactional view/method.
|
94 |
"""
|
95 |
user.save() |
96 |
self.post_store_user(user, request)
|
97 |
return user
|
98 |
|
99 |
def post_store_user(self, user, request): |
100 |
"""
|
101 |
Interface method for descendant backends to be able to do stuff within
|
102 |
the transaction enabled by store_user.
|
103 |
"""
|
104 |
pass
|
105 |
|
106 |
|
107 |
class LocalUserCreationForm(UserCreationForm, StoreUserMixin): |
108 |
"""
|
109 |
Extends the built in UserCreationForm in several ways:
|
110 |
|
111 |
* Adds email, first_name, last_name, recaptcha_challenge_field,
|
112 |
* recaptcha_response_field field.
|
113 |
* The username field isn't visible and it is assigned a generated id.
|
114 |
* User created is not active.
|
115 |
"""
|
116 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
117 |
recaptcha_response_field = forms.CharField( |
118 |
widget=RecaptchaWidget, label='')
|
119 |
|
120 |
class Meta: |
121 |
model = AstakosUser |
122 |
fields = ("email", "first_name", "last_name", |
123 |
"has_signed_terms", "has_signed_terms") |
124 |
|
125 |
def __init__(self, *args, **kwargs): |
126 |
"""
|
127 |
Changes the order of fields, and removes the username field.
|
128 |
"""
|
129 |
request = kwargs.pop('request', None) |
130 |
if request:
|
131 |
self.ip = request.META.get('REMOTE_ADDR', |
132 |
request.META.get('HTTP_X_REAL_IP', None)) |
133 |
|
134 |
super(LocalUserCreationForm, self).__init__(*args, **kwargs) |
135 |
self.fields.keyOrder = ['email', 'first_name', 'last_name', |
136 |
'password1', 'password2'] |
137 |
|
138 |
if RECAPTCHA_ENABLED:
|
139 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
140 |
'recaptcha_response_field', ])
|
141 |
if get_latest_terms():
|
142 |
self.fields.keyOrder.append('has_signed_terms') |
143 |
|
144 |
if 'has_signed_terms' in self.fields: |
145 |
# Overriding field label since we need to apply a link
|
146 |
# to the terms within the label
|
147 |
terms_link_html = '<a href="%s" target="_blank">%s</a>' \
|
148 |
% (reverse('latest_terms'), _("the terms")) |
149 |
self.fields['has_signed_terms'].label = \ |
150 |
mark_safe("I agree with %s" % terms_link_html)
|
151 |
|
152 |
def clean_email(self): |
153 |
email = self.cleaned_data['email'] |
154 |
if not email: |
155 |
raise forms.ValidationError(_(astakos_messages.REQUIRED_FIELD))
|
156 |
if reserved_verified_email(email):
|
157 |
raise forms.ValidationError(_(astakos_messages.EMAIL_USED))
|
158 |
return email
|
159 |
|
160 |
def clean_has_signed_terms(self): |
161 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
162 |
if not has_signed_terms: |
163 |
raise forms.ValidationError(_(astakos_messages.SIGN_TERMS))
|
164 |
return has_signed_terms
|
165 |
|
166 |
def clean_recaptcha_response_field(self): |
167 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
168 |
self.validate_captcha()
|
169 |
return self.cleaned_data['recaptcha_response_field'] |
170 |
|
171 |
def clean_recaptcha_challenge_field(self): |
172 |
if 'recaptcha_response_field' in self.cleaned_data: |
173 |
self.validate_captcha()
|
174 |
return self.cleaned_data['recaptcha_challenge_field'] |
175 |
|
176 |
def validate_captcha(self): |
177 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
178 |
rrf = self.cleaned_data['recaptcha_response_field'] |
179 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
180 |
if not check.is_valid: |
181 |
raise forms.ValidationError(_(astakos_messages.CAPTCHA_VALIDATION_ERR))
|
182 |
|
183 |
def post_store_user(self, user, request): |
184 |
"""
|
185 |
Interface method for descendant backends to be able to do stuff within
|
186 |
the transaction enabled by store_user.
|
187 |
"""
|
188 |
user.add_auth_provider('local', auth_backend='astakos') |
189 |
user.set_password(self.cleaned_data['password1']) |
190 |
|
191 |
def save(self, commit=True): |
192 |
"""
|
193 |
Saves the email, first_name and last_name properties, after the normal
|
194 |
save behavior is complete.
|
195 |
"""
|
196 |
user = super(LocalUserCreationForm, self).save(commit=False) |
197 |
user.renew_token() |
198 |
if commit:
|
199 |
user.save() |
200 |
logger.log(LOGGING_LEVEL, 'Created user %s' % user.email)
|
201 |
return user
|
202 |
|
203 |
|
204 |
class InvitedLocalUserCreationForm(LocalUserCreationForm): |
205 |
"""
|
206 |
Extends the LocalUserCreationForm: email is readonly.
|
207 |
"""
|
208 |
class Meta: |
209 |
model = AstakosUser |
210 |
fields = ("email", "first_name", "last_name", "has_signed_terms") |
211 |
|
212 |
def __init__(self, *args, **kwargs): |
213 |
"""
|
214 |
Changes the order of fields, and removes the username field.
|
215 |
"""
|
216 |
super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs) |
217 |
|
218 |
#set readonly form fields
|
219 |
ro = ('email', 'username',) |
220 |
for f in ro: |
221 |
self.fields[f].widget.attrs['readonly'] = True |
222 |
|
223 |
def save(self, commit=True): |
224 |
user = super(InvitedLocalUserCreationForm, self).save(commit=False) |
225 |
user.set_invitations_level() |
226 |
user.email_verified = True
|
227 |
if commit:
|
228 |
user.save() |
229 |
return user
|
230 |
|
231 |
|
232 |
class ThirdPartyUserCreationForm(forms.ModelForm, StoreUserMixin): |
233 |
id = forms.CharField( |
234 |
widget=forms.HiddenInput(), |
235 |
label='',
|
236 |
required=False
|
237 |
) |
238 |
third_party_identifier = forms.CharField( |
239 |
widget=forms.HiddenInput(), |
240 |
label=''
|
241 |
) |
242 |
email = forms.EmailField( |
243 |
label='Contact email',
|
244 |
help_text = 'We will use this email to contact you'
|
245 |
) |
246 |
|
247 |
class Meta: |
248 |
model = AstakosUser |
249 |
fields = ['id', 'email', 'third_party_identifier', |
250 |
'first_name', 'last_name', 'has_signed_terms'] |
251 |
|
252 |
def __init__(self, *args, **kwargs): |
253 |
"""
|
254 |
Changes the order of fields, and removes the username field.
|
255 |
"""
|
256 |
self.request = kwargs.get('request', None) |
257 |
if self.request: |
258 |
kwargs.pop('request')
|
259 |
|
260 |
super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs) |
261 |
|
262 |
if not get_latest_terms(): |
263 |
del self.fields['has_signed_terms'] |
264 |
|
265 |
if 'has_signed_terms' in self.fields: |
266 |
# Overriding field label since we need to apply a link
|
267 |
# to the terms within the label
|
268 |
terms_link_html = '<a href="%s" target="_blank">%s</a>' \
|
269 |
% (reverse('latest_terms'), _("the terms")) |
270 |
self.fields['has_signed_terms'].label = \ |
271 |
mark_safe("I agree with %s" % terms_link_html)
|
272 |
|
273 |
def clean_email(self): |
274 |
email = self.cleaned_data['email'] |
275 |
if not email: |
276 |
raise forms.ValidationError(_(astakos_messages.REQUIRED_FIELD))
|
277 |
if reserved_verified_email(email):
|
278 |
provider = auth_providers.get_provider(self.request.REQUEST.get('provider', 'local')) |
279 |
extra_message = _(astakos_messages.EXISTING_EMAIL_THIRD_PARTY_NOTIFICATION) % \ |
280 |
(provider.get_title_display, reverse('edit_profile'))
|
281 |
|
282 |
raise forms.ValidationError(_(astakos_messages.EMAIL_USED) + ' ' + \ |
283 |
extra_message) |
284 |
return email
|
285 |
|
286 |
def clean_has_signed_terms(self): |
287 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
288 |
if not has_signed_terms: |
289 |
raise forms.ValidationError(_(astakos_messages.SIGN_TERMS))
|
290 |
return has_signed_terms
|
291 |
|
292 |
def post_store_user(self, user, request): |
293 |
pending = PendingThirdPartyUser.objects.get( |
294 |
token=request.POST.get('third_party_token'),
|
295 |
third_party_identifier= \ |
296 |
self.cleaned_data.get('third_party_identifier')) |
297 |
return user.add_pending_auth_provider(pending)
|
298 |
|
299 |
def save(self, commit=True): |
300 |
user = super(ThirdPartyUserCreationForm, self).save(commit=False) |
301 |
user.set_unusable_password() |
302 |
user.renew_token() |
303 |
if commit:
|
304 |
user.save() |
305 |
logger.log(LOGGING_LEVEL, 'Created user %s' % user.email)
|
306 |
return user
|
307 |
|
308 |
|
309 |
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm): |
310 |
"""
|
311 |
Extends the ThirdPartyUserCreationForm: email is readonly.
|
312 |
"""
|
313 |
def __init__(self, *args, **kwargs): |
314 |
"""
|
315 |
Changes the order of fields, and removes the username field.
|
316 |
"""
|
317 |
super(
|
318 |
InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
|
319 |
|
320 |
#set readonly form fields
|
321 |
ro = ('email',)
|
322 |
for f in ro: |
323 |
self.fields[f].widget.attrs['readonly'] = True |
324 |
|
325 |
def save(self, commit=True): |
326 |
user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False) |
327 |
user.set_invitation_level() |
328 |
user.email_verified = True
|
329 |
if commit:
|
330 |
user.save() |
331 |
return user
|
332 |
|
333 |
|
334 |
class ShibbolethUserCreationForm(ThirdPartyUserCreationForm): |
335 |
additional_email = forms.CharField( |
336 |
widget=forms.HiddenInput(), label='', required=False) |
337 |
|
338 |
def __init__(self, *args, **kwargs): |
339 |
super(ShibbolethUserCreationForm, self).__init__(*args, **kwargs) |
340 |
# copy email value to additional_mail in case user will change it
|
341 |
name = 'email'
|
342 |
field = self.fields[name]
|
343 |
self.initial['additional_email'] = self.initial.get(name, field.initial) |
344 |
self.initial['email'] = None |
345 |
|
346 |
|
347 |
class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, |
348 |
InvitedThirdPartyUserCreationForm): |
349 |
pass
|
350 |
|
351 |
|
352 |
class LoginForm(AuthenticationForm): |
353 |
username = forms.EmailField(label=_("Email"))
|
354 |
recaptcha_challenge_field = forms.CharField(widget=DummyWidget) |
355 |
recaptcha_response_field = forms.CharField( |
356 |
widget=RecaptchaWidget, label='')
|
357 |
|
358 |
def __init__(self, *args, **kwargs): |
359 |
was_limited = kwargs.get('was_limited', False) |
360 |
request = kwargs.get('request', None) |
361 |
if request:
|
362 |
self.ip = request.META.get('REMOTE_ADDR', |
363 |
request.META.get('HTTP_X_REAL_IP', None)) |
364 |
|
365 |
t = ('request', 'was_limited') |
366 |
for elem in t: |
367 |
if elem in kwargs.keys(): |
368 |
kwargs.pop(elem) |
369 |
super(LoginForm, self).__init__(*args, **kwargs) |
370 |
|
371 |
self.fields.keyOrder = ['username', 'password'] |
372 |
if was_limited and RECAPTCHA_ENABLED: |
373 |
self.fields.keyOrder.extend(['recaptcha_challenge_field', |
374 |
'recaptcha_response_field', ])
|
375 |
|
376 |
def clean_username(self): |
377 |
return self.cleaned_data['username'].lower() |
378 |
|
379 |
def clean_recaptcha_response_field(self): |
380 |
if 'recaptcha_challenge_field' in self.cleaned_data: |
381 |
self.validate_captcha()
|
382 |
return self.cleaned_data['recaptcha_response_field'] |
383 |
|
384 |
def clean_recaptcha_challenge_field(self): |
385 |
if 'recaptcha_response_field' in self.cleaned_data: |
386 |
self.validate_captcha()
|
387 |
return self.cleaned_data['recaptcha_challenge_field'] |
388 |
|
389 |
def validate_captcha(self): |
390 |
rcf = self.cleaned_data['recaptcha_challenge_field'] |
391 |
rrf = self.cleaned_data['recaptcha_response_field'] |
392 |
check = captcha.submit(rcf, rrf, RECAPTCHA_PRIVATE_KEY, self.ip)
|
393 |
if not check.is_valid: |
394 |
raise forms.ValidationError(_(astakos_messages.CAPTCHA_VALIDATION_ERR))
|
395 |
|
396 |
def clean(self): |
397 |
"""
|
398 |
Override default behavior in order to check user's activation later
|
399 |
"""
|
400 |
username = self.cleaned_data.get('username') |
401 |
|
402 |
if username:
|
403 |
try:
|
404 |
user = AstakosUser.objects.get_by_identifier(username) |
405 |
if not user.has_auth_provider('local'): |
406 |
provider = auth_providers.get_provider('local')
|
407 |
raise forms.ValidationError(
|
408 |
_(provider.get_message('NOT_ACTIVE_FOR_USER')))
|
409 |
except AstakosUser.DoesNotExist:
|
410 |
pass
|
411 |
|
412 |
try:
|
413 |
super(LoginForm, self).clean() |
414 |
except forms.ValidationError, e:
|
415 |
if self.user_cache is None: |
416 |
raise
|
417 |
if not self.user_cache.is_active: |
418 |
raise forms.ValidationError(self.user_cache.get_inactive_message()) |
419 |
if self.request: |
420 |
if not self.request.session.test_cookie_worked(): |
421 |
raise
|
422 |
return self.cleaned_data |
423 |
|
424 |
|
425 |
class ProfileForm(forms.ModelForm): |
426 |
"""
|
427 |
Subclass of ``ModelForm`` for permiting user to edit his/her profile.
|
428 |
Most of the fields are readonly since the user is not allowed to change
|
429 |
them.
|
430 |
|
431 |
The class defines a save method which sets ``is_verified`` to True so as the
|
432 |
user during the next login will not to be redirected to profile page.
|
433 |
"""
|
434 |
renew = forms.BooleanField(label='Renew token', required=False) |
435 |
|
436 |
class Meta: |
437 |
model = AstakosUser |
438 |
fields = ('email', 'first_name', 'last_name', 'auth_token', |
439 |
'auth_token_expires')
|
440 |
|
441 |
def __init__(self, *args, **kwargs): |
442 |
self.session_key = kwargs.pop('session_key', None) |
443 |
super(ProfileForm, self).__init__(*args, **kwargs) |
444 |
instance = getattr(self, 'instance', None) |
445 |
ro_fields = ('email', 'auth_token', 'auth_token_expires') |
446 |
if instance and instance.id: |
447 |
for field in ro_fields: |
448 |
self.fields[field].widget.attrs['readonly'] = True |
449 |
|
450 |
def save(self, commit=True): |
451 |
user = super(ProfileForm, self).save(commit=False) |
452 |
user.is_verified = True
|
453 |
if self.cleaned_data.get('renew'): |
454 |
user.renew_token( |
455 |
flush_sessions=True,
|
456 |
current_key=self.session_key
|
457 |
) |
458 |
if commit:
|
459 |
user.save() |
460 |
return user
|
461 |
|
462 |
|
463 |
|
464 |
class FeedbackForm(forms.Form): |
465 |
"""
|
466 |
Form for writing feedback.
|
467 |
"""
|
468 |
feedback_msg = forms.CharField(widget=forms.Textarea, label=u'Message')
|
469 |
feedback_data = forms.CharField(widget=forms.HiddenInput(), label='',
|
470 |
required=False)
|
471 |
|
472 |
|
473 |
class SendInvitationForm(forms.Form): |
474 |
"""
|
475 |
Form for sending an invitations
|
476 |
"""
|
477 |
|
478 |
email = forms.EmailField(required=True, label='Email address') |
479 |
first_name = forms.EmailField(label='First name')
|
480 |
last_name = forms.EmailField(label='Last name')
|
481 |
|
482 |
|
483 |
class ExtendedPasswordResetForm(PasswordResetForm): |
484 |
"""
|
485 |
Extends PasswordResetForm by overriding
|
486 |
|
487 |
save method: to pass a custom from_email in send_mail.
|
488 |
clean_email: to handle local auth provider checks
|
489 |
"""
|
490 |
def clean_email(self): |
491 |
email = super(ExtendedPasswordResetForm, self).clean_email() |
492 |
try:
|
493 |
user = AstakosUser.objects.get_by_identifier(email) |
494 |
|
495 |
if not user.is_active: |
496 |
raise forms.ValidationError(_(astakos_messages.ACCOUNT_INACTIVE))
|
497 |
|
498 |
if not user.has_usable_password(): |
499 |
raise forms.ValidationError(_(astakos_messages.UNUSABLE_PASSWORD))
|
500 |
|
501 |
if not user.can_change_password(): |
502 |
raise forms.ValidationError(_(astakos_messages.AUTH_PROVIDER_CANNOT_CHANGE_PASSWORD))
|
503 |
except AstakosUser.DoesNotExist, e:
|
504 |
raise forms.ValidationError(_(astakos_messages.EMAIL_UNKNOWN))
|
505 |
return email
|
506 |
|
507 |
def save( |
508 |
self, domain_override=None, email_template_name='registration/password_reset_email.html', |
509 |
use_https=False, token_generator=default_token_generator, request=None): |
510 |
"""
|
511 |
Generates a one-use only link for resetting password and sends to the user.
|
512 |
"""
|
513 |
for user in self.users_cache: |
514 |
url = user.astakosuser.get_password_reset_url(token_generator) |
515 |
url = urljoin(BASEURL, url) |
516 |
t = loader.get_template(email_template_name) |
517 |
c = { |
518 |
'email': user.email,
|
519 |
'url': url,
|
520 |
'site_name': SITENAME,
|
521 |
'user': user,
|
522 |
'baseurl': BASEURL,
|
523 |
'support': DEFAULT_CONTACT_EMAIL
|
524 |
} |
525 |
from_email = settings.SERVER_EMAIL |
526 |
send_mail(_(PASSWORD_RESET_EMAIL_SUBJECT), |
527 |
t.render(Context(c)), |
528 |
from_email, |
529 |
[user.email], |
530 |
connection=get_connection) |
531 |
|
532 |
|
533 |
class EmailChangeForm(forms.ModelForm): |
534 |
|
535 |
class Meta: |
536 |
model = EmailChange |
537 |
fields = ('new_email_address',)
|
538 |
|
539 |
def clean_new_email_address(self): |
540 |
addr = self.cleaned_data['new_email_address'] |
541 |
if reserved_verified_email(addr):
|
542 |
raise forms.ValidationError(_(astakos_messages.EMAIL_USED))
|
543 |
return addr
|
544 |
|
545 |
def save(self, request, email_template_name='registration/email_change_email.txt', commit=True): |
546 |
ec = super(EmailChangeForm, self).save(commit=False) |
547 |
ec.user = request.user |
548 |
# delete pending email changes
|
549 |
request.user.emailchanges.all().delete() |
550 |
|
551 |
activation_key = hashlib.sha1( |
552 |
str(random()) + smart_str(ec.new_email_address))
|
553 |
ec.activation_key = activation_key.hexdigest() |
554 |
if commit:
|
555 |
ec.save() |
556 |
send_change_email(ec, request, email_template_name=email_template_name) |
557 |
|
558 |
|
559 |
class SignApprovalTermsForm(forms.ModelForm): |
560 |
|
561 |
class Meta: |
562 |
model = AstakosUser |
563 |
fields = ("has_signed_terms",)
|
564 |
|
565 |
def __init__(self, *args, **kwargs): |
566 |
super(SignApprovalTermsForm, self).__init__(*args, **kwargs) |
567 |
|
568 |
def clean_has_signed_terms(self): |
569 |
has_signed_terms = self.cleaned_data['has_signed_terms'] |
570 |
if not has_signed_terms: |
571 |
raise forms.ValidationError(_(astakos_messages.SIGN_TERMS))
|
572 |
return has_signed_terms
|
573 |
|
574 |
|
575 |
class InvitationForm(forms.ModelForm): |
576 |
|
577 |
username = forms.EmailField(label=_("Email"))
|
578 |
|
579 |
def __init__(self, *args, **kwargs): |
580 |
super(InvitationForm, self).__init__(*args, **kwargs) |
581 |
|
582 |
class Meta: |
583 |
model = Invitation |
584 |
fields = ('username', 'realname') |
585 |
|
586 |
def clean_username(self): |
587 |
username = self.cleaned_data['username'] |
588 |
try:
|
589 |
Invitation.objects.get(username=username) |
590 |
raise forms.ValidationError(_(astakos_messages.INVITATION_EMAIL_EXISTS))
|
591 |
except Invitation.DoesNotExist:
|
592 |
pass
|
593 |
return username
|
594 |
|
595 |
|
596 |
class ExtendedPasswordChangeForm(PasswordChangeForm): |
597 |
"""
|
598 |
Extends PasswordChangeForm by enabling user
|
599 |
to optionally renew also the token.
|
600 |
"""
|
601 |
if not NEWPASSWD_INVALIDATE_TOKEN: |
602 |
renew = forms.BooleanField(label='Renew token', required=False, |
603 |
initial=True,
|
604 |
help_text='Unsetting this may result in security risk.')
|
605 |
|
606 |
def __init__(self, user, *args, **kwargs): |
607 |
self.session_key = kwargs.pop('session_key', None) |
608 |
super(ExtendedPasswordChangeForm, self).__init__(user, *args, **kwargs) |
609 |
|
610 |
def save(self, commit=True): |
611 |
try:
|
612 |
if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'): |
613 |
self.user.renew_token()
|
614 |
self.user.flush_sessions(current_key=self.session_key) |
615 |
except AttributeError: |
616 |
# if user model does has not such methods
|
617 |
pass
|
618 |
return super(ExtendedPasswordChangeForm, self).save(commit=commit) |
619 |
|
620 |
class ExtendedSetPasswordForm(SetPasswordForm): |
621 |
"""
|
622 |
Extends SetPasswordForm by enabling user
|
623 |
to optionally renew also the token.
|
624 |
"""
|
625 |
if not NEWPASSWD_INVALIDATE_TOKEN: |
626 |
renew = forms.BooleanField( |
627 |
label='Renew token',
|
628 |
required=False,
|
629 |
initial=True,
|
630 |
help_text='Unsetting this may result in security risk.')
|
631 |
|
632 |
def __init__(self, user, *args, **kwargs): |
633 |
super(ExtendedSetPasswordForm, self).__init__(user, *args, **kwargs) |
634 |
|
635 |
@transaction.commit_on_success()
|
636 |
def save(self, commit=True): |
637 |
try:
|
638 |
self.user = AstakosUser.objects.get(id=self.user.id) |
639 |
if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'): |
640 |
self.user.renew_token()
|
641 |
#self.user.flush_sessions()
|
642 |
if not self.user.has_auth_provider('local'): |
643 |
self.user.add_auth_provider('local', auth_backend='astakos') |
644 |
|
645 |
except BaseException, e: |
646 |
logger.exception(e) |
647 |
return super(ExtendedSetPasswordForm, self).save(commit=commit) |
648 |
|
649 |
|
650 |
|
651 |
|
652 |
app_name_label = "Project name"
|
653 |
app_name_placeholder = _("myproject.mylab.ntua.gr")
|
654 |
app_name_validator = validators.RegexValidator( |
655 |
DOMAIN_VALUE_REGEX, |
656 |
_(astakos_messages.DOMAIN_VALUE_ERR), |
657 |
'invalid')
|
658 |
app_name_help = _("""
|
659 |
The Project's name should be in a domain format.
|
660 |
The domain shouldn't neccessarily exist in the real
|
661 |
world but is helpful to imply a structure.
|
662 |
e.g.: myproject.mylab.ntua.gr or
|
663 |
myservice.myteam.myorganization""")
|
664 |
app_name_widget = forms.TextInput( |
665 |
attrs={'placeholder': app_name_placeholder})
|
666 |
|
667 |
|
668 |
app_home_label = "Homepage URL"
|
669 |
app_home_placeholder = 'myinstitution.org/myproject/'
|
670 |
app_home_help = _("""
|
671 |
URL pointing at your project's site.
|
672 |
e.g.: myinstitution.org/myproject/.
|
673 |
Leave blank if there is no website.""")
|
674 |
app_home_widget = forms.TextInput( |
675 |
attrs={'placeholder': app_home_placeholder})
|
676 |
|
677 |
app_desc_label = _("Description")
|
678 |
app_desc_help = _("""
|
679 |
Please provide a short but descriptive abstract of your Project,
|
680 |
so that anyone searching can quickly understand
|
681 |
what this Project is about.""")
|
682 |
|
683 |
app_comment_label = _("Comments for review (private)")
|
684 |
app_comment_help = _("""
|
685 |
Write down any comments you may have for the reviewer
|
686 |
of this application (e.g. background and rationale to
|
687 |
support your request).
|
688 |
The comments are strictly for the review process
|
689 |
and will not be published.""")
|
690 |
|
691 |
app_start_date_label = _("Start date")
|
692 |
app_start_date_help = _("""
|
693 |
Provide a date when your need your project to be created,
|
694 |
and members to be able to join and get resources.
|
695 |
This date is only a hint to help prioritize reviews.""")
|
696 |
|
697 |
app_end_date_label = _("Termination date")
|
698 |
app_end_date_help = _("""
|
699 |
At this date, the project will be automatically terminated
|
700 |
and its resource grants revoked from all members.
|
701 |
Unless you know otherwise,
|
702 |
it is best to start with a conservative estimation.
|
703 |
You can always re-apply for an extension, if you need.""")
|
704 |
|
705 |
join_policy_label = _("Joining policy")
|
706 |
app_member_join_policy_help = _("""
|
707 |
Text fo member_join_policy.""")
|
708 |
leave_policy_label = _("Leaving policy")
|
709 |
app_member_leave_policy_help = _("""
|
710 |
Text fo member_leave_policy.""")
|
711 |
|
712 |
max_members_label = _("Maximum member count")
|
713 |
max_members_help = _("""
|
714 |
Specify the maximum number of members this project may have,
|
715 |
including the owner. Beyond this number, no new members
|
716 |
may join the project and be granted the project resources.
|
717 |
Unless you certainly for otherwise,
|
718 |
it is best to start with a conservative limit.
|
719 |
You can always request a raise when you need it.""")
|
720 |
|
721 |
join_policies = PROJECT_MEMBER_JOIN_POLICIES.iteritems() |
722 |
leave_policies = PROJECT_MEMBER_LEAVE_POLICIES.iteritems() |
723 |
|
724 |
class ProjectApplicationForm(forms.ModelForm): |
725 |
|
726 |
name = forms.CharField( |
727 |
label = app_name_label, |
728 |
help_text = app_name_help, |
729 |
widget = app_name_widget, |
730 |
validators = [app_name_validator]) |
731 |
|
732 |
homepage = forms.URLField( |
733 |
label = app_home_label, |
734 |
help_text = app_home_help, |
735 |
widget = app_home_widget, |
736 |
required = False)
|
737 |
|
738 |
description = forms.CharField( |
739 |
label = app_desc_label, |
740 |
help_text = app_desc_help, |
741 |
widget = forms.Textarea, |
742 |
required = False)
|
743 |
|
744 |
comments = forms.CharField( |
745 |
label = app_comment_label, |
746 |
help_text = app_comment_help, |
747 |
widget = forms.Textarea, |
748 |
required = False)
|
749 |
|
750 |
start_date = forms.DateTimeField( |
751 |
label = app_start_date_label, |
752 |
help_text = app_start_date_help, |
753 |
required = False)
|
754 |
|
755 |
end_date = forms.DateTimeField( |
756 |
label = app_end_date_label, |
757 |
help_text = app_end_date_help) |
758 |
|
759 |
member_join_policy = forms.TypedChoiceField( |
760 |
label = join_policy_label, |
761 |
help_text = app_member_join_policy_help, |
762 |
initial = 2,
|
763 |
coerce = int,
|
764 |
choices = join_policies) |
765 |
|
766 |
member_leave_policy = forms.TypedChoiceField( |
767 |
label = leave_policy_label, |
768 |
help_text = app_member_leave_policy_help, |
769 |
coerce = int,
|
770 |
choices = leave_policies) |
771 |
|
772 |
limit_on_members_number = forms.IntegerField( |
773 |
label = max_members_label, |
774 |
help_text = max_members_help, |
775 |
required = False)
|
776 |
|
777 |
class Meta: |
778 |
model = ProjectApplication |
779 |
fields = ( 'name', 'homepage', 'description', |
780 |
'start_date', 'end_date', 'comments', |
781 |
'member_join_policy', 'member_leave_policy', |
782 |
'limit_on_members_number')
|
783 |
|
784 |
def __init__(self, *args, **kwargs): |
785 |
instance = kwargs.get('instance')
|
786 |
self.precursor_application = instance
|
787 |
super(ProjectApplicationForm, self).__init__(*args, **kwargs) |
788 |
# in case of new application remove closed join policy
|
789 |
if not instance: |
790 |
policies = PROJECT_MEMBER_JOIN_POLICIES.copy() |
791 |
policies.pop('3')
|
792 |
self.fields['member_join_policy'].choices = policies.iteritems() |
793 |
|
794 |
def clean_start_date(self): |
795 |
start_date = self.cleaned_data.get('start_date') |
796 |
if not self.precursor_application: |
797 |
today = datetime.now() |
798 |
today = datetime(today.year, today.month, today.day) |
799 |
if start_date and (start_date - today).days < 0: |
800 |
raise forms.ValidationError(
|
801 |
_(astakos_messages.INVALID_PROJECT_START_DATE)) |
802 |
return start_date
|
803 |
|
804 |
def clean_end_date(self): |
805 |
start_date = self.cleaned_data.get('start_date') |
806 |
end_date = self.cleaned_data.get('end_date') |
807 |
today = datetime.now() |
808 |
today = datetime(today.year, today.month, today.day) |
809 |
if end_date and (end_date - today).days < 0: |
810 |
raise forms.ValidationError(
|
811 |
_(astakos_messages.INVALID_PROJECT_END_DATE)) |
812 |
if start_date and (end_date - start_date).days <= 0: |
813 |
raise forms.ValidationError(
|
814 |
_(astakos_messages.INCONSISTENT_PROJECT_DATES)) |
815 |
return end_date
|
816 |
|
817 |
def clean(self): |
818 |
userid = self.data.get('user', None) |
819 |
self.user = None |
820 |
if userid:
|
821 |
try:
|
822 |
self.user = AstakosUser.objects.get(id=userid)
|
823 |
except AstakosUser.DoesNotExist:
|
824 |
pass
|
825 |
if not self.user: |
826 |
raise forms.ValidationError(_(astakos_messages.NO_APPLICANT))
|
827 |
super(ProjectApplicationForm, self).clean() |
828 |
return self.cleaned_data |
829 |
|
830 |
@property
|
831 |
def resource_policies(self): |
832 |
policies = [] |
833 |
append = policies.append |
834 |
for name, value in self.data.iteritems(): |
835 |
if not value: |
836 |
continue
|
837 |
uplimit = value |
838 |
if name.endswith('_uplimit'): |
839 |
subs = name.split('_uplimit')
|
840 |
prefix, suffix = subs |
841 |
s, sep, r = prefix.partition(RESOURCE_SEPARATOR) |
842 |
resource = Resource.objects.get(service__name=s, name=r) |
843 |
|
844 |
# keep only resource limits for selected resource groups
|
845 |
if self.data.get( |
846 |
'is_selected_%s' % resource.group, "0" |
847 |
) == "1":
|
848 |
d = model_to_dict(resource) |
849 |
if uplimit:
|
850 |
d.update(dict(service=s, resource=r, uplimit=uplimit))
|
851 |
else:
|
852 |
d.update(dict(service=s, resource=r, uplimit=None)) |
853 |
append(d) |
854 |
|
855 |
return policies
|
856 |
|
857 |
def save(self, commit=True): |
858 |
data = dict(self.cleaned_data) |
859 |
data['precursor_application'] = self.instance.id |
860 |
data['owner'] = self.user |
861 |
data['resource_policies'] = self.resource_policies |
862 |
submit_application(data, request_user=self.user)
|
863 |
|
864 |
class ProjectSortForm(forms.Form): |
865 |
sorting = forms.ChoiceField( |
866 |
label='Sort by',
|
867 |
choices=(('name', 'Sort by Name'), |
868 |
('issue_date', 'Sort by Issue date'), |
869 |
('start_date', 'Sort by Start Date'), |
870 |
('end_date', 'Sort by End Date'), |
871 |
# ('approved_members_num', 'Sort by Participants'),
|
872 |
('state', 'Sort by Status'), |
873 |
('member_join_policy__description', 'Sort by Member Join Policy'), |
874 |
('member_leave_policy__description', 'Sort by Member Leave Policy'), |
875 |
('-name', 'Sort by Name'), |
876 |
('-issue_date', 'Sort by Issue date'), |
877 |
('-start_date', 'Sort by Start Date'), |
878 |
('-end_date', 'Sort by End Date'), |
879 |
# ('-approved_members_num', 'Sort by Participants'),
|
880 |
('-state', 'Sort by Status'), |
881 |
('-member_join_policy__description', 'Sort by Member Join Policy'), |
882 |
('-member_leave_policy__description', 'Sort by Member Leave Policy') |
883 |
), |
884 |
required=True
|
885 |
) |
886 |
|
887 |
class AddProjectMembersForm(forms.Form): |
888 |
q = forms.CharField( |
889 |
max_length=800, widget=forms.Textarea, label=_('Add members'), |
890 |
help_text=_(astakos_messages.ADD_PROJECT_MEMBERS_Q_HELP), required=True)
|
891 |
|
892 |
def __init__(self, *args, **kwargs): |
893 |
chain_id = kwargs.pop('chain_id', None) |
894 |
if chain_id:
|
895 |
self.project = Project.objects.get(id=chain_id)
|
896 |
self.request_user = kwargs.pop('request_user', None) |
897 |
super(AddProjectMembersForm, self).__init__(*args, **kwargs) |
898 |
|
899 |
def clean(self): |
900 |
try:
|
901 |
accept_membership_checks(self.project, self.request_user) |
902 |
except PermissionDenied, e:
|
903 |
raise forms.ValidationError(e)
|
904 |
|
905 |
q = self.cleaned_data.get('q') or '' |
906 |
users = q.split(',')
|
907 |
users = list(u.strip() for u in users if u) |
908 |
db_entries = AstakosUser.objects.filter(email__in=users) |
909 |
unknown = list(set(users) - set(u.email for u in db_entries)) |
910 |
if unknown:
|
911 |
raise forms.ValidationError(
|
912 |
_(astakos_messages.UNKNOWN_USERS) % ','.join(unknown))
|
913 |
self.valid_users = db_entries
|
914 |
return self.cleaned_data |
915 |
|
916 |
def get_valid_users(self): |
917 |
"""Should be called after form cleaning"""
|
918 |
try:
|
919 |
return self.valid_users |
920 |
except:
|
921 |
return ()
|
922 |
|
923 |
class ProjectMembersSortForm(forms.Form): |
924 |
sorting = forms.ChoiceField( |
925 |
label='Sort by',
|
926 |
choices=(('person__email', 'User Id'), |
927 |
('person__first_name', 'Name'), |
928 |
('acceptance_date', 'Acceptance date') |
929 |
), |
930 |
required=True
|
931 |
) |
932 |
|
933 |
|
934 |
class ProjectSearchForm(forms.Form): |
935 |
q = forms.CharField(max_length=200, label='Search project', required=False) |
936 |
|
937 |
|
938 |
class ExtendedProfileForm(ProfileForm): |
939 |
"""
|
940 |
Profile form that combines `email change` and `password change` user
|
941 |
actions by propagating submited data to internal EmailChangeForm
|
942 |
and ExtendedPasswordChangeForm objects.
|
943 |
"""
|
944 |
|
945 |
password_change_form = None
|
946 |
email_change_form = None
|
947 |
|
948 |
password_change = False
|
949 |
email_change = False
|
950 |
|
951 |
extra_forms_fields = { |
952 |
'email': ['new_email_address'], |
953 |
'password': ['old_password', 'new_password1', 'new_password2'] |
954 |
} |
955 |
|
956 |
fields = ('email')
|
957 |
change_password = forms.BooleanField(initial=False, required=False) |
958 |
change_email = forms.BooleanField(initial=False, required=False) |
959 |
|
960 |
email_changed = False
|
961 |
password_changed = False
|
962 |
|
963 |
def __init__(self, *args, **kwargs): |
964 |
session_key = kwargs.get('session_key', None) |
965 |
self.fields_list = [
|
966 |
'email',
|
967 |
'new_email_address',
|
968 |
'first_name',
|
969 |
'last_name',
|
970 |
'auth_token',
|
971 |
'auth_token_expires',
|
972 |
'old_password',
|
973 |
'new_password1',
|
974 |
'new_password2',
|
975 |
'change_email',
|
976 |
'change_password',
|
977 |
] |
978 |
|
979 |
super(ExtendedProfileForm, self).__init__(*args, **kwargs) |
980 |
self.session_key = session_key
|
981 |
if self.instance.can_change_password(): |
982 |
self.password_change = True |
983 |
else:
|
984 |
self.fields_list.remove('old_password') |
985 |
self.fields_list.remove('new_password1') |
986 |
self.fields_list.remove('new_password2') |
987 |
self.fields_list.remove('change_password') |
988 |
del self.fields['change_password'] |
989 |
|
990 |
|
991 |
if EMAILCHANGE_ENABLED and self.instance.can_change_email(): |
992 |
self.email_change = True |
993 |
else:
|
994 |
self.fields_list.remove('new_email_address') |
995 |
self.fields_list.remove('change_email') |
996 |
del self.fields['change_email'] |
997 |
|
998 |
self._init_extra_forms()
|
999 |
self.save_extra_forms = []
|
1000 |
self.success_messages = []
|
1001 |
self.fields.keyOrder = self.fields_list |
1002 |
|
1003 |
|
1004 |
def _init_extra_form_fields(self): |
1005 |
|
1006 |
|
1007 |
if self.email_change: |
1008 |
self.fields.update(self.email_change_form.fields) |
1009 |
self.fields['new_email_address'].required = False |
1010 |
|
1011 |
if self.password_change: |
1012 |
self.fields.update(self.password_change_form.fields) |
1013 |
self.fields['old_password'].required = False |
1014 |
self.fields['old_password'].label = _('Password') |
1015 |
self.fields['old_password'].initial = 'password' |
1016 |
self.fields['new_password1'].required = False |
1017 |
self.fields['new_password2'].required = False |
1018 |
|
1019 |
def _update_extra_form_errors(self): |
1020 |
if self.cleaned_data.get('change_password'): |
1021 |
self.errors.update(self.password_change_form.errors) |
1022 |
if self.cleaned_data.get('change_email'): |
1023 |
self.errors.update(self.email_change_form.errors) |
1024 |
|
1025 |
def _init_extra_forms(self): |
1026 |
self.email_change_form = EmailChangeForm(self.data) |
1027 |
self.password_change_form = ExtendedPasswordChangeForm(user=self.instance, |
1028 |
data=self.data, session_key=self.session_key) |
1029 |
self._init_extra_form_fields()
|
1030 |
|
1031 |
def is_valid(self): |
1032 |
password, email = True, True |
1033 |
profile = super(ExtendedProfileForm, self).is_valid() |
1034 |
if profile and self.cleaned_data.get('change_password', None): |
1035 |
password = self.password_change_form.is_valid()
|
1036 |
self.save_extra_forms.append('password') |
1037 |
if profile and self.cleaned_data.get('change_email'): |
1038 |
email = self.email_change_form.is_valid()
|
1039 |
self.save_extra_forms.append('email') |
1040 |
|
1041 |
if not password or not email: |
1042 |
self._update_extra_form_errors()
|
1043 |
|
1044 |
return all([profile, password, email]) |
1045 |
|
1046 |
def save(self, request, *args, **kwargs): |
1047 |
if 'email' in self.save_extra_forms: |
1048 |
self.email_change_form.save(request, *args, **kwargs)
|
1049 |
self.email_changed = True |
1050 |
if 'password' in self.save_extra_forms: |
1051 |
self.password_change_form.save(*args, **kwargs)
|
1052 |
self.password_changed = True |
1053 |
return super(ExtendedProfileForm, self).save(*args, **kwargs) |
1054 |
|