auth.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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"), max_length=254)
  13. password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
  14. error_messages = {
  15. 'invalid_login': _("Your login or password is incorrect. Please try again."),
  16. 'inactive': _("This account is inactive."),
  17. }
  18. def clean(self):
  19. username = self.cleaned_data.get('username')
  20. password = self.cleaned_data.get('password')
  21. if username and password:
  22. self.user_cache = authenticate(username=username,
  23. password=password)
  24. if self.user_cache is None:
  25. raise ValidationError(
  26. self.error_messages['invalid_login'],
  27. code='invalid_login',
  28. )
  29. else:
  30. self.confirm_login_allowed(self.user_cache)
  31. return self.cleaned_data
  32. class AdminAuthenticationForm(AuthenticationForm):
  33. required_css_class = 'required'
  34. def __init__(self, *args, **kwargs):
  35. self.error_messages.update({
  36. 'not_staff': _("Your account does not have admin privileges.")
  37. })
  38. def confirm_login_allowed(self, user):
  39. if not user.is_staff:
  40. raise forms.ValidationError(
  41. self.error_messages['not_staff'],
  42. code='not_staff',
  43. )