auth.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. '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. def confirm_login_allowed(self, user):
  42. # TODO: CHECK ACTIVATION AND BANS
  43. pass
  44. class AdminAuthenticationForm(AuthenticationForm):
  45. required_css_class = 'required'
  46. def __init__(self, *args, **kwargs):
  47. self.error_messages.update({
  48. 'not_staff': _("Your account does not have admin privileges.")
  49. })
  50. super(AdminAuthenticationForm, self).__init__(*args, **kwargs)
  51. def confirm_login_allowed(self, user):
  52. if not user.is_staff:
  53. raise forms.ValidationError(
  54. self.error_messages['not_staff'],
  55. code='not_staff',
  56. )