forms.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import hashlib
  2. from django.core.exceptions import ValidationError
  3. from django.utils.translation import ugettext_lazy as _
  4. import floppyforms as forms
  5. from misago.forms import Form
  6. from misago.models import User
  7. from misago.validators import validate_password, validate_email
  8. class CredentialsChangeForm(Form):
  9. new_email = forms.EmailField(label=_('New E-mail'),
  10. help_text=_("Enter new e-mail address or leave this field empty if you want only to change your password."),
  11. max_length=255, required=False)
  12. new_password = forms.CharField(label=_('New Password'),
  13. help_text=_("Enter new password or leave this empty if you only want to change your e-mail address."),
  14. max_length=255, widget=forms.PasswordInput, required=False)
  15. current_password = forms.CharField(label= _('Current Password'),
  16. help_text=_("Confirm changes by entering your current password."),
  17. max_length=255, widget=forms.PasswordInput)
  18. def clean_new_email(self):
  19. if self.cleaned_data['new_email']:
  20. new_hash = hashlib.md5(self.cleaned_data['new_email'].lower()).hexdigest()
  21. if new_hash == self.request.user.email_hash:
  22. raise ValidationError(_("New e-mail is same as your current e-mail."))
  23. try:
  24. User.objects.get(email_hash=new_hash)
  25. raise ValidationError(_("New e-mail address is already in use by other member."))
  26. except User.DoesNotExist:
  27. pass
  28. validate_email(self.cleaned_data['new_email'])
  29. return self.cleaned_data['new_email'].lower()
  30. def clean_new_password(self):
  31. if self.cleaned_data['new_password']:
  32. validate_password(self.cleaned_data['new_password'])
  33. return self.cleaned_data['new_password']
  34. def clean_current_password(self):
  35. if not self.request.user.check_password(self.cleaned_data['current_password']):
  36. raise ValidationError(_("You have entered wrong password."))
  37. return ''
  38. def clean(self):
  39. cleaned_data = super(CredentialsChangeForm, self).clean()
  40. if not cleaned_data['new_email'] and not cleaned_data['new_password']:
  41. raise ValidationError(_("You have to enter either new e-mail address or new password."))
  42. return cleaned_data