X-Git-Url: https://code.grnet.gr/git/astakos/blobdiff_plain/ab8f79561772ac354e11f9f17e4c3f8740783302..ee210d1dbeac6b1ff43a9119cbcaeae7138282f1:/snf-astakos-app/astakos/im/forms.py diff --git a/snf-astakos-app/astakos/im/forms.py b/snf-astakos-app/astakos/im/forms.py index 8afce79..b3d2be1 100644 --- a/snf-astakos-app/astakos/im/forms.py +++ b/snf-astakos-app/astakos/im/forms.py @@ -35,7 +35,8 @@ from datetime import datetime from django import forms from django.utils.translation import ugettext as _ -from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, PasswordResetForm +from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, \ + PasswordResetForm, PasswordChangeForm, SetPasswordForm from django.core.mail import send_mail from django.contrib.auth.tokens import default_token_generator from django.template import Context, loader @@ -44,16 +45,23 @@ from django.core.urlresolvers import reverse from django.utils.functional import lazy from django.utils.safestring import mark_safe from django.contrib import messages +from django.utils.encoding import smart_str -from astakos.im.models import AstakosUser, Invitation -from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL, RECAPTCHA_ENABLED -from astakos.im.widgets import DummyWidget, RecaptchaWidget, ApprovalTermsWidget +from astakos.im.models import AstakosUser, Invitation, get_latest_terms, EmailChange +from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, \ + BASEURL, SITENAME, RECAPTCHA_PRIVATE_KEY, DEFAULT_CONTACT_EMAIL, \ + RECAPTCHA_ENABLED, LOGGING_LEVEL, PASSWORD_RESET_EMAIL_SUBJECT, \ + NEWPASSWD_INVALIDATE_TOKEN +from astakos.im.widgets import DummyWidget, RecaptchaWidget +from astakos.im.functions import send_change_email # since Django 1.4 use django.core.urlresolvers.reverse_lazy instead -from astakos.im.util import reverse_lazy, get_latest_terms, reserved_email, get_query +from astakos.im.util import reverse_lazy, reserved_email, get_query import logging +import hashlib import recaptcha.client.captcha as captcha +from random import random logger = logging.getLogger(__name__) @@ -70,8 +78,7 @@ class LocalUserCreationForm(UserCreationForm): class Meta: model = AstakosUser - fields = ("email", "first_name", "last_name", "has_signed_terms") - widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))} + fields = ("email", "first_name", "last_name", "has_signed_terms", "has_signed_terms") def __init__(self, *args, **kwargs): """ @@ -82,15 +89,16 @@ class LocalUserCreationForm(UserCreationForm): kwargs.pop('request') self.ip = request.META.get('REMOTE_ADDR', request.META.get('HTTP_X_REAL_IP', None)) - + super(LocalUserCreationForm, self).__init__(*args, **kwargs) self.fields.keyOrder = ['email', 'first_name', 'last_name', 'password1', 'password2'] - if get_latest_terms(): - self.fields.keyOrder.append('has_signed_terms') + if RECAPTCHA_ENABLED: self.fields.keyOrder.extend(['recaptcha_challenge_field', 'recaptcha_response_field',]) + if get_latest_terms(): + self.fields.keyOrder.append('has_signed_terms') if 'has_signed_terms' in self.fields: # Overriding field label since we need to apply a link @@ -140,20 +148,16 @@ class LocalUserCreationForm(UserCreationForm): user.renew_token() if commit: user.save() - logger.info('Created user %s', user) + logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, []) return user class InvitedLocalUserCreationForm(LocalUserCreationForm): """ - Extends the LocalUserCreationForm: adds an inviter readonly field. + Extends the LocalUserCreationForm: email is readonly. """ - - inviter = forms.CharField(widget=forms.TextInput(), label=_('Inviter Real Name')) - class Meta: model = AstakosUser fields = ("email", "first_name", "last_name", "has_signed_terms") - widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))} def __init__(self, *args, **kwargs): """ @@ -162,10 +166,10 @@ class InvitedLocalUserCreationForm(LocalUserCreationForm): super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs) #set readonly form fields - ro = ('inviter', 'email', 'username',) + ro = ('email', 'username',) for f in ro: self.fields[f].widget.attrs['readonly'] = True - + def save(self, commit=True): user = super(InvitedLocalUserCreationForm, self).save(commit=False) @@ -180,9 +184,8 @@ class InvitedLocalUserCreationForm(LocalUserCreationForm): class ThirdPartyUserCreationForm(forms.ModelForm): class Meta: model = AstakosUser - fields = ("email", "first_name", "last_name", "third_party_identifier") - widgets = {"has_signed_terms":ApprovalTermsWidget(terms_uri=reverse_lazy('latest_terms'))} - + fields = ("email", "first_name", "last_name", "third_party_identifier", "has_signed_terms") + def __init__(self, *args, **kwargs): """ Changes the order of fields, and removes the username field. @@ -195,10 +198,10 @@ class ThirdPartyUserCreationForm(forms.ModelForm): if get_latest_terms(): self.fields.keyOrder.append('has_signed_terms') #set readonly form fields - ro = ["third_party_identifier", "first_name", "last_name"] + ro = ["third_party_identifier"] for f in ro: self.fields[f].widget.attrs['readonly'] = True - + if 'has_signed_terms' in self.fields: # Overriding field label since we need to apply a link # to the terms within the label @@ -206,19 +209,19 @@ class ThirdPartyUserCreationForm(forms.ModelForm): % (reverse('latest_terms'), _("the terms")) self.fields['has_signed_terms'].label = \ mark_safe("I agree with %s" % terms_link_html) - + def clean_email(self): email = self.cleaned_data['email'] if not email: raise forms.ValidationError(_("This field is required")) return email - + def clean_has_signed_terms(self): has_signed_terms = self.cleaned_data['has_signed_terms'] if not has_signed_terms: raise forms.ValidationError(_('You have to agree with the terms')) return has_signed_terms - + def save(self, commit=True): user = super(ThirdPartyUserCreationForm, self).save(commit=False) user.set_unusable_password() @@ -226,15 +229,13 @@ class ThirdPartyUserCreationForm(forms.ModelForm): user.provider = get_query(self.request).get('provider') if commit: user.save() - logger.info('Created user %s', user) + logger._log(LOGGING_LEVEL, 'Created user %s' % user.email, []) return user class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm): """ - Extends the LocalUserCreationForm: adds an inviter readonly field. + Extends the ThirdPartyUserCreationForm: email is readonly. """ - inviter = forms.CharField(widget=forms.TextInput(), label=_('Inviter Real Name')) - def __init__(self, *args, **kwargs): """ Changes the order of fields, and removes the username field. @@ -242,10 +243,10 @@ class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm): super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs) #set readonly form fields - ro = ('inviter', 'email',) + ro = ('email',) for f in ro: self.fields[f].widget.attrs['readonly'] = True - + def save(self, commit=True): user = super(InvitedThirdPartyUserCreationForm, self).save(commit=False) level = user.invitation.inviter.level + 1 @@ -257,40 +258,53 @@ class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm): return user class ShibbolethUserCreationForm(ThirdPartyUserCreationForm): + additional_email = forms.CharField(widget=forms.HiddenInput(), label='', required = False) + + def __init__(self, *args, **kwargs): + super(ShibbolethUserCreationForm, self).__init__(*args, **kwargs) + self.fields.keyOrder.append('additional_email') + # copy email value to additional_mail in case user will change it + name = 'email' + field = self.fields[name] + self.initial['additional_email'] = self.initial.get(name, field.initial) + def clean_email(self): email = self.cleaned_data['email'] for user in AstakosUser.objects.filter(email = email): if user.provider == 'shibboleth': raise forms.ValidationError(_("This email is already associated with another shibboleth account.")) + elif not user.is_active: + raise forms.ValidationError(_("This email is already associated with an inactive account. \ + You need to wait to be activated before being able to switch to a shibboleth account.")) super(ShibbolethUserCreationForm, self).clean_email() return email class InvitedShibbolethUserCreationForm(ShibbolethUserCreationForm, InvitedThirdPartyUserCreationForm): pass - + class LoginForm(AuthenticationForm): username = forms.EmailField(label=_("Email")) recaptcha_challenge_field = forms.CharField(widget=DummyWidget) recaptcha_response_field = forms.CharField(widget=RecaptchaWidget, label='') - + def __init__(self, *args, **kwargs): was_limited = kwargs.get('was_limited', False) request = kwargs.get('request', None) if request: self.ip = request.META.get('REMOTE_ADDR', request.META.get('HTTP_X_REAL_IP', None)) - + t = ('request', 'was_limited') for elem in t: if elem in kwargs.keys(): kwargs.pop(elem) super(LoginForm, self).__init__(*args, **kwargs) - + self.fields.keyOrder = ['username', 'password'] if was_limited and RECAPTCHA_ENABLED: self.fields.keyOrder.extend(['recaptcha_challenge_field', 'recaptcha_response_field',]) - + def clean_recaptcha_response_field(self): if 'recaptcha_challenge_field' in self.cleaned_data: self.validate_captcha() @@ -308,6 +322,12 @@ class LoginForm(AuthenticationForm): if not check.is_valid: raise forms.ValidationError(_('You have not entered the correct words')) + def clean(self): + super(LoginForm, self).clean() + if self.user_cache and self.user_cache.provider not in ('local', ''): + raise forms.ValidationError(_('Local login is not the current authentication method for this account.')) + return self.cleaned_data + class ProfileForm(forms.ModelForm): """ Subclass of ``ModelForm`` for permiting user to edit his/her profile. @@ -373,7 +393,7 @@ class ExtendedPasswordResetForm(PasswordResetForm): except AstakosUser.DoesNotExist, e: raise forms.ValidationError(_('That e-mail address doesn\'t have an associated user account. Are you sure you\'ve registered?')) return email - + def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, request=None): """ @@ -383,20 +403,40 @@ class ExtendedPasswordResetForm(PasswordResetForm): url = reverse('django.contrib.auth.views.password_reset_confirm', kwargs={'uidb36':int_to_base36(user.id), 'token':token_generator.make_token(user)}) - url = request.build_absolute_uri(url) + url = urljoin(BASEURL, url) t = loader.get_template(email_template_name) c = { 'email': user.email, 'url': url, 'site_name': SITENAME, 'user': user, - 'baseurl': request.build_absolute_uri(), + 'baseurl': BASEURL, 'support': DEFAULT_CONTACT_EMAIL } from_email = DEFAULT_FROM_EMAIL - send_mail(_("Password reset on %s alpha2 testing") % SITENAME, + send_mail(_(PASSWORD_RESET_EMAIL_SUBJECT), t.render(Context(c)), from_email, [user.email]) +class EmailChangeForm(forms.ModelForm): + class Meta: + model = EmailChange + fields = ('new_email_address',) + + def clean_new_email_address(self): + addr = self.cleaned_data['new_email_address'] + if AstakosUser.objects.filter(email__iexact=addr): + raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.')) + return addr + + def save(self, email_template_name, request, commit=True): + ec = super(EmailChangeForm, self).save(commit=False) + ec.user = request.user + activation_key = hashlib.sha1(str(random()) + smart_str(ec.new_email_address)) + ec.activation_key=activation_key.hexdigest() + if commit: + ec.save() + send_change_email(ec, request, email_template_name=email_template_name) + class SignApprovalTermsForm(forms.ModelForm): class Meta: model = AstakosUser @@ -413,14 +453,14 @@ class SignApprovalTermsForm(forms.ModelForm): class InvitationForm(forms.ModelForm): username = forms.EmailField(label=_("Email")) - + def __init__(self, *args, **kwargs): super(InvitationForm, self).__init__(*args, **kwargs) - + class Meta: model = Invitation fields = ('username', 'realname') - + def clean_username(self): username = self.cleaned_data['username'] try: @@ -429,3 +469,50 @@ class InvitationForm(forms.ModelForm): except Invitation.DoesNotExist: pass return username + +class ExtendedPasswordChangeForm(PasswordChangeForm): + """ + Extends PasswordChangeForm by enabling user + to optionally renew also the token. + """ + if not NEWPASSWD_INVALIDATE_TOKEN: + renew = forms.BooleanField(label='Renew token', required=False, + initial=True, + help_text='Unsetting this may result in security risk.') + + def __init__(self, user, *args, **kwargs): + super(ExtendedPasswordChangeForm, self).__init__(user, *args, **kwargs) + + def save(self, commit=True): + user = super(ExtendedPasswordChangeForm, self).save(commit=False) + if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'): + user.renew_token() + if commit: + user.save() + return user + +class ExtendedSetPasswordForm(SetPasswordForm): + """ + Extends SetPasswordForm by enabling user + to optionally renew also the token. + """ + if not NEWPASSWD_INVALIDATE_TOKEN: + renew = forms.BooleanField(label='Renew token', required=False, + initial=True, + help_text='Unsetting this may result in security risk.') + + def __init__(self, user, *args, **kwargs): + super(ExtendedSetPasswordForm, self).__init__(user, *args, **kwargs) + + def save(self, commit=True): + user = super(ExtendedSetPasswordForm, self).save(commit=False) + if NEWPASSWD_INVALIDATE_TOKEN or self.cleaned_data.get('renew'): + try: + user = AstakosUser.objects.get(id=user.id) + except AstakosUser.DoesNotExist: + pass + else: + user.renew_token() + if commit: + user.save() + return user \ No newline at end of file