serializers.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import hashlib
  2. import hmac
  3. from allauth.account import app_settings
  4. from allauth.account.adapter import get_adapter
  5. from allauth.account.forms import default_token_generator
  6. from allauth.account.models import EmailAddress
  7. from allauth.account.utils import filter_users_by_email
  8. from allauth.socialaccount.models import SocialApp
  9. from dj_rest_auth.registration.serializers import (
  10. RegisterSerializer as BaseRegisterSerializer,
  11. )
  12. from dj_rest_auth.registration.serializers import (
  13. SocialAccountSerializer as BaseSocialAccountSerializer,
  14. )
  15. from dj_rest_auth.serializers import PasswordResetSerializer
  16. from django.conf import settings
  17. from django.utils.translation import gettext_lazy as _
  18. from adrf.serializers import ModelSerializer
  19. from rest_framework import serializers
  20. from glitchtip.constants import SOCIAL_ADAPTER_MAP
  21. from .forms import PasswordSetAndResetForm
  22. from .models import User
  23. class SocialAccountSerializer(BaseSocialAccountSerializer):
  24. email = serializers.SerializerMethodField()
  25. username = serializers.SerializerMethodField()
  26. class Meta(BaseSocialAccountSerializer.Meta):
  27. fields = (
  28. "id",
  29. "provider",
  30. "uid",
  31. "last_login",
  32. "date_joined",
  33. "email",
  34. "username",
  35. )
  36. def get_email(self, obj):
  37. if obj.extra_data:
  38. if "email" in obj.extra_data:
  39. return obj.extra_data.get("email")
  40. return obj.extra_data.get("userPrincipalName") # MS oauth uses this
  41. def get_username(self, obj):
  42. if obj.extra_data:
  43. return obj.extra_data.get("username")
  44. class SocialAppSerializer(ModelSerializer):
  45. authorize_url = serializers.SerializerMethodField()
  46. scopes = serializers.SerializerMethodField()
  47. class Meta:
  48. model = SocialApp
  49. fields = ("provider", "name", "client_id", "authorize_url", "scopes")
  50. def get_authorize_url(self, obj):
  51. request = self.context.get("request")
  52. adapter = SOCIAL_ADAPTER_MAP.get(obj.provider, obj.provider_id)(request)
  53. if adapter:
  54. return adapter.authorize_url
  55. def get_scopes(self, obj):
  56. request = self.context.get("request")
  57. if request:
  58. provider = obj.get_provider(request)
  59. return provider.get_scope(request)
  60. class ConfirmEmailAddressSerializer(serializers.Serializer):
  61. email = serializers.EmailField()
  62. class EmailAddressSerializer(ModelSerializer):
  63. isPrimary = serializers.BooleanField(source="primary", read_only=True)
  64. email = serializers.EmailField() # Remove default unique validation
  65. isVerified = serializers.BooleanField(source="verified", read_only=True)
  66. class Meta:
  67. model = EmailAddress
  68. fields = ("isPrimary", "email", "isVerified")
  69. def clean_email(self):
  70. """Validate email as done in allauth.account.forms.AddEmailForm"""
  71. value = self.cleaned_data["email"]
  72. value = get_adapter().clean_email(value)
  73. errors = {
  74. "this_account": _(
  75. "This e-mail address is already associated" " with this account."
  76. ),
  77. "different_account": _(
  78. "This e-mail address is already associated" " with another account."
  79. ),
  80. }
  81. users = filter_users_by_email(value)
  82. on_this_account = [u for u in users if u.pk == self.user.pk]
  83. on_diff_account = [u for u in users if u.pk != self.user.pk]
  84. if on_this_account:
  85. raise serializers.ValidationError(errors["this_account"])
  86. if on_diff_account and app_settings.UNIQUE_EMAIL:
  87. raise serializers.ValidationError(errors["different_account"])
  88. return value
  89. def validate(self, attrs):
  90. if self.context["request"].method == "POST":
  91. # Run extra validation on create
  92. self.user = self.context["request"].user
  93. self.cleaned_data = attrs
  94. attrs["email"] = self.clean_email()
  95. return attrs
  96. def create(self, validated_data):
  97. return EmailAddress.objects.add_email(
  98. self.context["request"], self.user, validated_data["email"], confirm=True
  99. )
  100. def update(self, instance, validated_data):
  101. instance.primary = True
  102. instance.save()
  103. return instance
  104. class UserSerializer(ModelSerializer):
  105. username = serializers.CharField(source="email", read_only=True)
  106. lastLogin = serializers.DateTimeField(source="last_login", read_only=True)
  107. isSuperuser = serializers.BooleanField(source="is_superuser")
  108. emails = EmailAddressSerializer(many=True, default=[])
  109. identities = SocialAccountSerializer(
  110. source="socialaccount_set", many=True, read_only=True
  111. )
  112. id = serializers.CharField()
  113. isActive = serializers.BooleanField(source="is_active")
  114. dateJoined = serializers.DateTimeField(source="created", read_only=True)
  115. hasPasswordAuth = serializers.BooleanField(
  116. source="has_usable_password", read_only=True
  117. )
  118. class Meta:
  119. model = User
  120. fields = (
  121. "username",
  122. "lastLogin",
  123. "isSuperuser",
  124. "emails",
  125. "identities",
  126. "id",
  127. "isActive",
  128. "name",
  129. "dateJoined",
  130. "hasPasswordAuth",
  131. "email",
  132. "options",
  133. )
  134. class CurrentUserSerializer(UserSerializer):
  135. chatwootIdentifierHash = serializers.SerializerMethodField()
  136. class Meta(UserSerializer.Meta):
  137. fields = UserSerializer.Meta.fields + ("chatwootIdentifierHash",)
  138. def get_chatwootIdentifierHash(self, obj):
  139. if settings.CHATWOOT_WEBSITE_TOKEN and settings.CHATWOOT_IDENTITY_TOKEN:
  140. secret = bytes(settings.CHATWOOT_IDENTITY_TOKEN, "utf-8")
  141. message = bytes(str(obj.id), "utf-8")
  142. hash = hmac.new(secret, message, hashlib.sha256)
  143. return hash.hexdigest()
  144. class RegisterSerializer(BaseRegisterSerializer):
  145. tags = serializers.CharField(
  146. write_only=True,
  147. allow_blank=True,
  148. required=False,
  149. help_text="Additional UTM (analytics) data",
  150. )
  151. def custom_signup(self, request, user):
  152. tags = self.validated_data.get("tags")
  153. if tags:
  154. user.set_register_analytics_tags(tags)
  155. user.save(update_fields=["analytics"])
  156. class UserNotificationsSerializer(ModelSerializer):
  157. subscribeByDefault = serializers.BooleanField(source="subscribe_by_default")
  158. class Meta:
  159. model = User
  160. fields = ("subscribeByDefault",)
  161. class NoopTokenSerializer(serializers.Serializer):
  162. """dj-rest-auth requires tokens, but we don't use them."""
  163. class PasswordSetResetSerializer(PasswordResetSerializer):
  164. password_reset_form_class = PasswordSetAndResetForm
  165. def save(self):
  166. request = self.context.get("request")
  167. opts = {
  168. "use_https": request.is_secure(),
  169. "from_email": getattr(settings, "DEFAULT_FROM_EMAIL"),
  170. "request": request,
  171. "token_generator": default_token_generator,
  172. "subject_template_name": "registration/password_reset_subject.txt",
  173. "email_template_name": "registration/password_reset_email.txt",
  174. "html_email_template_name": "registration/password_reset_email.html",
  175. }
  176. opts.update(self.get_email_options())
  177. self.reset_form.save(**opts)