auth.py 5.2 KB

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