auth.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. "
  20. "Please try again."),
  21. 'inactive': _("This account is inactive."),
  22. }
  23. def clean(self):
  24. username = self.cleaned_data.get('username')
  25. password = self.cleaned_data.get('password')
  26. if username and password:
  27. self.user_cache = authenticate(username=username,
  28. password=password)
  29. if self.user_cache is None:
  30. raise ValidationError(
  31. self.error_messages['invalid_login'],
  32. code='invalid_login',
  33. )
  34. else:
  35. self.confirm_login_allowed(self.user_cache)
  36. else:
  37. raise ValidationError(
  38. self.error_messages['empty_data'],
  39. code='empty_data',
  40. )
  41. return self.cleaned_data
  42. def confirm_login_allowed(self, user):
  43. # TODO: CHECK ACTIVATION AND BANS
  44. pass
  45. class AdminAuthenticationForm(AuthenticationForm):
  46. required_css_class = 'required'
  47. def __init__(self, *args, **kwargs):
  48. self.error_messages.update({
  49. 'not_staff': _("Your account does not have admin privileges.")
  50. })
  51. super(AdminAuthenticationForm, self).__init__(*args, **kwargs)
  52. def confirm_login_allowed(self, user):
  53. if not user.is_staff:
  54. raise forms.ValidationError(
  55. self.error_messages['not_staff'],
  56. code='not_staff',
  57. )