auth.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. from rest_framework import serializers
  2. from django.contrib.auth import get_user_model
  3. from django.contrib.auth.password_validation import validate_password
  4. from django.core.exceptions import ValidationError
  5. from django.urls import reverse
  6. from django.utils.translation import ugettext_lazy, ugettext as _
  7. from misago.acl import serialize_acl
  8. from misago.users.authmixin import AuthMixin
  9. from misago.users.tokens import is_password_change_token_valid
  10. from .user import UserSerializer
  11. UserModel = get_user_model()
  12. class AuthenticatedUserSerializer(UserSerializer):
  13. email = serializers.SerializerMethodField()
  14. class Meta:
  15. model = UserModel
  16. fields = UserSerializer.Meta.fields + [
  17. 'is_hiding_presence',
  18. 'limits_private_thread_invites_to',
  19. 'unread_private_threads',
  20. 'subscribe_to_started_threads',
  21. 'subscribe_to_replied_threads',
  22. ]
  23. def get_acl(self, obj):
  24. return serialize_acl(obj)
  25. def get_email(self, obj):
  26. return obj.email
  27. def get_api(self, obj):
  28. return {
  29. 'avatar': reverse('misago:api:user-avatar', kwargs={'pk': obj.pk}),
  30. 'details': reverse('misago:api:user-details', kwargs={'pk': obj.pk}),
  31. 'change_email': reverse('misago:api:user-change-email', kwargs={'pk': obj.pk}),
  32. 'change_password': reverse('misago:api:user-change-password', kwargs={'pk': obj.pk}),
  33. 'edit_details': reverse('misago:api:user-edit-details', kwargs={'pk': obj.pk}),
  34. 'options': reverse('misago:api:user-forum-options', kwargs={'pk': obj.pk}),
  35. 'username': reverse('misago:api:user-username', kwargs={'pk': obj.pk}),
  36. }
  37. AuthenticatedUserSerializer = AuthenticatedUserSerializer.exclude_fields(
  38. 'is_avatar_locked',
  39. 'is_blocked',
  40. 'is_followed',
  41. 'is_signature_locked',
  42. 'meta',
  43. 'signature',
  44. 'status',
  45. )
  46. class AnonymousUserSerializer(serializers.Serializer):
  47. id = serializers.ReadOnlyField()
  48. acl = serializers.SerializerMethodField()
  49. def get_acl(self, obj):
  50. if hasattr(obj, 'acl_cache'):
  51. return serialize_acl(obj)
  52. else:
  53. return {}
  54. class LoginSerializer(serializers.Serializer, AuthMixin):
  55. username = serializers.CharField(max_length=255)
  56. password = serializers.CharField(max_length=255, trim_whitespace=False)
  57. def validate(self, data):
  58. user = self.authenticate(data.get('username'), data.get('password'))
  59. self.confirm_login_allowed(user)
  60. return {'user': user}
  61. class GetUserSerializer(serializers.Serializer, AuthMixin):
  62. email = serializers.EmailField(max_length=255)
  63. def validate(self, data):
  64. user = self.get_user_by_email(data.get('email'))
  65. self.confirm_allowed(user)
  66. return {'user': user}
  67. def confirm_allowed(self, user):
  68. """override this method to include additional checks"""
  69. pass
  70. class ResendActivationSerializer(GetUserSerializer):
  71. def confirm_allowed(self, user):
  72. username_format = {'user': user.username}
  73. if not user.requires_activation:
  74. message = _("%(user)s, your account is already active.")
  75. raise ValidationError(message % username_format)
  76. if user.requires_activation_by_admin:
  77. message = _("%(user)s, only administrator may activate your account.")
  78. raise ValidationError(message % username_format)
  79. class SendPasswordFormSerializer(GetUserSerializer):
  80. auth_messages = {
  81. 'inactive_user': ugettext_lazy(
  82. "You have to activate your account before "
  83. "you will be able to request new password."
  84. ),
  85. 'inactive_admin': ugettext_lazy(
  86. "Administrator has to activate your account before "
  87. "you will be able to request new password."
  88. ),
  89. }
  90. def confirm_allowed(self, user):
  91. self.confirm_user_active(user)
  92. class ChangeForgottenPasswordSerializer(serializers.Serializer, AuthMixin):
  93. password = serializers.CharField(
  94. max_length=255,
  95. trim_whitespace=False,
  96. )
  97. token = serializers.CharField(max_length=255)
  98. auth_messages = {
  99. 'inactive_user': ugettext_lazy(
  100. "You have to activate your account before "
  101. "you will be able to change your password."
  102. ),
  103. 'inactive_admin': ugettext_lazy(
  104. "Administrator has to activate your account before "
  105. "you will be able to change your password."
  106. ),
  107. }
  108. def confirm_allowed(self):
  109. self.confirm_user_active(self.instance)
  110. self.confirm_user_not_banned(self.instance)
  111. def validate_password(self, value):
  112. validate_password(value, user=self.instance)
  113. return value
  114. def validate_token(self, value):
  115. if not is_password_change_token_valid(self.instance, value):
  116. raise ValidationError(_("Form link is invalid or expired. Please try again."))
  117. return value
  118. def validate(self, data):
  119. self.confirm_allowed()
  120. return data
  121. def save(self):
  122. self.instance.set_password(self.validated_data['password'])
  123. self.instance.save()