forms.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from django import forms
  2. from django.contrib.auth import authenticate
  3. from django.contrib.auth.forms import AuthenticationForm as BaseAuthenticationForm
  4. from django.core.exceptions import ValidationError
  5. from django.utils.translation import ugettext_lazy as _
  6. from misago.users.authmixin import AuthMixin
  7. class AdminAuthenticationForm(BaseAuthenticationForm, AuthMixin):
  8. username = forms.CharField(
  9. label=_("Username or e-mail"),
  10. required=False,
  11. max_length=254,
  12. )
  13. password = forms.CharField(
  14. label=_("Password"),
  15. strip=False,
  16. required=False,
  17. widget=forms.PasswordInput,
  18. )
  19. error_messages = {
  20. 'empty_data': _("Fill out both fields."),
  21. 'invalid_login': _("Login or password is incorrect."),
  22. 'not_staff': _("Your account does not have admin privileges."),
  23. }
  24. required_css_class = 'required'
  25. def clean(self):
  26. username = self.cleaned_data.get('username')
  27. password = self.cleaned_data.get('password')
  28. if username and password:
  29. self.user_cache = authenticate(username=username, password=password)
  30. if self.user_cache is None or not self.user_cache.is_active:
  31. raise ValidationError(self.error_messages['invalid_login'], code='invalid_login')
  32. else:
  33. self.confirm_login_allowed(self.user_cache)
  34. else:
  35. raise ValidationError(self.error_messages['empty_data'], code='empty_data')
  36. return self.cleaned_data
  37. def confirm_login_allowed(self, user):
  38. if not user.is_staff:
  39. raise ValidationError(self.error_messages['not_staff'], code='not_staff')