auth.py 5.1 KB

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