auth.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. from django.contrib.auth import authenticate, get_user_model
  2. from django.contrib.auth.forms import AuthenticationForm as BaseAuthenticationForm
  3. from django.core.exceptions import ValidationError
  4. from django.core.validators import validate_email
  5. from django.utils.translation import ugettext_lazy as _
  6. from misago.core import forms
  7. from ..bans import get_user_ban
  8. from ..validators import validate_password
  9. class MisagoAuthMixin(object):
  10. error_messages = {
  11. 'empty_data': _("Fill out both fields."),
  12. 'invalid_login': _("Login or password is incorrect."),
  13. 'inactive_user': _("You have to activate your account before "
  14. "you will be able to sign in."),
  15. 'inactive_admin': _("Your account has to be activated by "
  16. "Administrator before you will be able "
  17. "to sign in."),
  18. }
  19. def confirm_user_active(self, user):
  20. if user.requires_activation_by_admin:
  21. raise ValidationError(
  22. self.error_messages['inactive_admin'], code='inactive_admin')
  23. if user.requires_activation_by_user:
  24. raise ValidationError(
  25. self.error_messages['inactive_user'], code='inactive_user')
  26. def confirm_user_not_banned(self, user):
  27. if not user.is_staff:
  28. self.user_ban = get_user_ban(user)
  29. if self.user_ban:
  30. raise ValidationError('', code='banned')
  31. def get_errors_dict(self):
  32. error = self.errors.as_data()['__all__'][0]
  33. if error.code == 'banned':
  34. error.message = self.user_ban.ban.get_serialized_message()
  35. else:
  36. error.message = error.messages[0]
  37. return {
  38. 'detail': error.message,
  39. 'code': error.code
  40. }
  41. class AuthenticationForm(MisagoAuthMixin, BaseAuthenticationForm):
  42. """
  43. Base class for authenticating users, Floppy-forms and
  44. Misago login field comliant
  45. """
  46. username = forms.CharField(
  47. label=_("Username or e-mail"),
  48. required=False,
  49. max_length=254
  50. )
  51. password = forms.CharField(
  52. label=_("Password"),
  53. required=False,
  54. widget=forms.PasswordInput
  55. )
  56. def clean(self):
  57. username = self.cleaned_data.get('username')
  58. password = self.cleaned_data.get('password')
  59. if username and password:
  60. self.user_cache = authenticate(
  61. username=username, password=password)
  62. if self.user_cache is None or not self.user_cache.is_active:
  63. raise ValidationError(
  64. self.error_messages['invalid_login'], code='invalid_login')
  65. else:
  66. self.confirm_login_allowed(self.user_cache)
  67. else:
  68. raise ValidationError(
  69. self.error_messages['empty_data'], code='empty_data')
  70. return self.cleaned_data
  71. def confirm_login_allowed(self, user):
  72. self.confirm_user_active(user)
  73. self.confirm_user_not_banned(user)
  74. class AdminAuthenticationForm(AuthenticationForm):
  75. required_css_class = 'required'
  76. def __init__(self, *args, **kwargs):
  77. self.error_messages.update({
  78. 'not_staff': _("Your account does not have admin privileges.")
  79. })
  80. super(AdminAuthenticationForm, self).__init__(*args, **kwargs)
  81. def confirm_login_allowed(self, user):
  82. if not user.is_staff:
  83. raise forms.ValidationError(
  84. self.error_messages['not_staff'], code='not_staff')
  85. class GetUserForm(MisagoAuthMixin, forms.Form):
  86. email = forms.CharField()
  87. def clean(self):
  88. data = super(GetUserForm, self).clean()
  89. email = data.get('email')
  90. if not email or len(email) > 250:
  91. raise forms.ValidationError(
  92. _("Enter e-mail address."), code='empty_email')
  93. try:
  94. validate_email(email)
  95. except forms.ValidationError:
  96. raise forms.ValidationError(
  97. _("Entered e-mail is invalid."), code='invalid_email')
  98. try:
  99. User = get_user_model()
  100. user = User.objects.get_by_email(data['email'])
  101. if not user.is_active:
  102. raise User.DoesNotExist()
  103. self.user_cache = user
  104. except User.DoesNotExist:
  105. raise forms.ValidationError(
  106. _("No user with this e-mail exists."), code='not_found')
  107. self.confirm_allowed(user)
  108. return data
  109. def confirm_allowed(self, user):
  110. """override this method to include additional checks"""
  111. class ResendActivationForm(GetUserForm):
  112. def confirm_allowed(self, user):
  113. username_format = {'user': user.username}
  114. if not user.requires_activation:
  115. message = _("%(user)s, your account is already active.")
  116. raise forms.ValidationError(
  117. message % username_format, code='already_active')
  118. if user.requires_activation_by_admin:
  119. message = _("%(user)s, only administrator may activate your account.")
  120. raise forms.ValidationError(
  121. message % username_format, code='inactive_admin')
  122. class ResetPasswordForm(GetUserForm):
  123. error_messages = {
  124. 'inactive_user': _("You have to activate your account before "
  125. "you will be able to request new password."),
  126. 'inactive_admin': _("Administrator has to activate your account "
  127. "before you will be able to request "
  128. "new password."),
  129. }
  130. def confirm_allowed(self, user):
  131. self.confirm_user_active(user)