auth.py 5.2 KB

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