forms.py 2.5 KB

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