auth.py 5.3 KB

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