auth.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from django.core.exceptions import ValidationError
  2. from django.contrib.auth import authenticate
  3. from django.contrib.auth.forms import (AuthenticationForm as
  4. BaseAuthenticationForm)
  5. from django.utils.translation import ugettext_lazy as _
  6. from misago.core import forms
  7. class AuthenticationForm(forms.Form, BaseAuthenticationForm):
  8. """
  9. Base class for authenticating users, Floppy-forms and
  10. Misago login field comliant
  11. """
  12. username = forms.CharField(label=_("Username or e-mail"),
  13. required=False,
  14. max_length=254)
  15. password = forms.CharField(label=_("Password"), required=False,
  16. widget=forms.PasswordInput)
  17. error_messages = {
  18. 'empty_data': _("You have to fill out both fields."),
  19. 'invalid_login': _("Your login or password is incorrect. Please try again."),
  20. 'inactive': _("This account is inactive."),
  21. }
  22. def clean(self):
  23. username = self.cleaned_data.get('username')
  24. password = self.cleaned_data.get('password')
  25. if username and password:
  26. self.user_cache = authenticate(username=username,
  27. password=password)
  28. if self.user_cache is None:
  29. raise ValidationError(
  30. self.error_messages['invalid_login'],
  31. code='invalid_login',
  32. )
  33. else:
  34. self.confirm_login_allowed(self.user_cache)
  35. else:
  36. raise ValidationError(
  37. self.error_messages['empty_data'],
  38. code='empty_data',
  39. )
  40. return self.cleaned_data
  41. class AdminAuthenticationForm(AuthenticationForm):
  42. required_css_class = 'required'
  43. def __init__(self, *args, **kwargs):
  44. self.error_messages.update({
  45. 'not_staff': _("Your account does not have admin privileges.")
  46. })
  47. super(AdminAuthenticationForm, self).__init__(*args, **kwargs)
  48. def confirm_login_allowed(self, user):
  49. if not user.is_staff:
  50. raise forms.ValidationError(
  51. self.error_messages['not_staff'],
  52. code='not_staff',
  53. )