auth.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. from django.core.exceptions import ValidationError
  2. from django.contrib.auth import authenticate, get_user_model
  3. from django.contrib.auth.forms import (AuthenticationForm as
  4. BaseAuthenticationForm)
  5. from django.utils.translation import ugettext_lazy as _
  6. from misago.core import forms
  7. from misago.users.bans import get_user_ban
  8. from misago.users.validators import validate_password
  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 "
  14. "you will be able to sign in."),
  15. 'inactive_admin': _("Your account has to be activated by "
  16. "Administrator before you will be able "
  17. "to sign in."),
  18. }
  19. def confirm_user_active(self, user):
  20. if user.requires_activation_by_admin:
  21. raise ValidationError(
  22. self.error_messages['inactive_admin'],
  23. code='inactive_admin',
  24. )
  25. if user.requires_activation_by_user:
  26. raise ValidationError(
  27. self.error_messages['inactive_user'],
  28. code='inactive_user',
  29. )
  30. def confirm_user_not_banned(self, user):
  31. self.user_ban = get_user_ban(user)
  32. if self.user_ban:
  33. raise ValidationError('', code='banned')
  34. class AuthenticationForm(MisagoAuthMixin, forms.Form, BaseAuthenticationForm):
  35. """
  36. Base class for authenticating users, Floppy-forms and
  37. Misago login field comliant
  38. """
  39. username = forms.CharField(label=_("Username or e-mail"),
  40. required=False,
  41. max_length=254)
  42. password = forms.CharField(label=_("Password"), required=False,
  43. widget=forms.PasswordInput)
  44. def clean(self):
  45. username = self.cleaned_data.get('username')
  46. password = self.cleaned_data.get('password')
  47. if username and password:
  48. self.user_cache = authenticate(username=username,
  49. password=password)
  50. if self.user_cache is None or not self.user_cache.is_active:
  51. raise ValidationError(
  52. self.error_messages['invalid_login'],
  53. code='invalid_login',
  54. )
  55. else:
  56. self.confirm_login_allowed(self.user_cache)
  57. else:
  58. raise ValidationError(
  59. self.error_messages['empty_data'],
  60. code='empty_data',
  61. )
  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(
  76. self.error_messages['not_staff'],
  77. code='not_staff',
  78. )
  79. class GetUserForm(MisagoAuthMixin, forms.Form):
  80. username = forms.CharField(label=_("Username or e-mail"))
  81. def clean(self):
  82. data = super(GetUserForm, self).clean()
  83. credential = data.get('username')
  84. if not credential or len(credential) > 250:
  85. raise forms.ValidationError(_("You have to fill out form."))
  86. try:
  87. User = get_user_model()
  88. user = User.objects.get_by_username_or_email(data['username'])
  89. self.user_cache = user
  90. except User.DoesNotExist:
  91. raise forms.ValidationError(_("Invalid username or e-mail."))
  92. self.confirm_allowed(user)
  93. return data
  94. def confirm_allowed(self, user):
  95. raise NotImplementedError("confirm_allowed method must be defined "
  96. "by inheriting classes")
  97. class ResendActivationForm(GetUserForm):
  98. def confirm_allowed(self, user):
  99. self.confirm_user_not_banned(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)
  104. if user.requires_activation_by_admin:
  105. message = _("%(user)s, only administrator may activate "
  106. "your account.")
  107. raise forms.ValidationError(message % username_format)
  108. class ResetPasswordForm(GetUserForm):
  109. error_messages = {
  110. 'inactive_user': _("You have to activate your account before "
  111. "you will be able to request new password."),
  112. 'inactive_admin': _("Administrator has to activate your account "
  113. "before you will be able to request "
  114. "new password."),
  115. }
  116. def confirm_allowed(self, user):
  117. self.confirm_user_not_banned(user)
  118. self.confirm_user_active(user)
  119. class SetNewPasswordForm(MisagoAuthMixin, forms.Form):
  120. new_password = forms.CharField(label=_("New password"),
  121. widget=forms.PasswordInput)
  122. def clean(self):
  123. data = super(SetNewPasswordForm, self).clean()
  124. new_password = data.get('new_password')
  125. if not new_password or len(new_password) > 250:
  126. raise forms.ValidationError(_("You have to fill out form."))
  127. validate_password(new_password)
  128. return data