serializers.py 6.7 KB

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