auth.py 5.2 KB

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