serializers.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. provider_name = (
  50. providers.registry.by_id(obj.provider).get_package().split(".")[-1]
  51. )
  52. request = self.context.get("request")
  53. adapter = SOCIAL_ADAPTER_MAP.get(provider_name, None)(request)
  54. if adapter:
  55. adapter.provider_id = obj.provider
  56. return adapter.authorize_url
  57. def get_scopes(self, obj):
  58. request = self.context.get("request")
  59. if request:
  60. provider = providers.registry.by_id(obj.provider, request)
  61. return provider.get_scope(request)
  62. class ConfirmEmailAddressSerializer(serializers.Serializer):
  63. email = serializers.EmailField()
  64. class EmailAddressSerializer(serializers.ModelSerializer):
  65. isPrimary = serializers.BooleanField(source="primary", read_only=True)
  66. email = serializers.EmailField() # Remove default unique validation
  67. isVerified = serializers.BooleanField(source="verified", read_only=True)
  68. class Meta:
  69. model = EmailAddress
  70. fields = ("isPrimary", "email", "isVerified")
  71. def clean_email(self):
  72. """Validate email as done in allauth.account.forms.AddEmailForm"""
  73. value = self.cleaned_data["email"]
  74. value = get_adapter().clean_email(value)
  75. errors = {
  76. "this_account": _(
  77. "This e-mail address is already associated" " with this account."
  78. ),
  79. "different_account": _(
  80. "This e-mail address is already associated" " with another account."
  81. ),
  82. }
  83. users = filter_users_by_email(value)
  84. on_this_account = [u for u in users if u.pk == self.user.pk]
  85. on_diff_account = [u for u in users if u.pk != self.user.pk]
  86. if on_this_account:
  87. raise serializers.ValidationError(errors["this_account"])
  88. if on_diff_account and app_settings.UNIQUE_EMAIL:
  89. raise serializers.ValidationError(errors["different_account"])
  90. return value
  91. def validate(self, attrs):
  92. if self.context["request"].method == "POST":
  93. # Run extra validation on create
  94. self.user = self.context["request"].user
  95. self.cleaned_data = attrs
  96. attrs["email"] = self.clean_email()
  97. return attrs
  98. def create(self, validated_data):
  99. return EmailAddress.objects.add_email(
  100. self.context["request"], self.user, validated_data["email"], confirm=True
  101. )
  102. def update(self, instance, validated_data):
  103. instance.primary = True
  104. instance.save()
  105. return instance
  106. class UserSerializer(serializers.ModelSerializer):
  107. username = serializers.CharField(source="email", read_only=True)
  108. lastLogin = serializers.DateTimeField(source="last_login", read_only=True)
  109. isSuperuser = serializers.BooleanField(source="is_superuser")
  110. emails = EmailAddressSerializer(many=True, default=[])
  111. identities = SocialAccountSerializer(
  112. source="socialaccount_set", many=True, read_only=True
  113. )
  114. id = serializers.CharField()
  115. isActive = serializers.BooleanField(source="is_active")
  116. dateJoined = serializers.DateTimeField(source="created", read_only=True)
  117. hasPasswordAuth = serializers.BooleanField(
  118. source="has_usable_password", read_only=True
  119. )
  120. class Meta:
  121. model = User
  122. fields = (
  123. "username",
  124. "lastLogin",
  125. "isSuperuser",
  126. "emails",
  127. "identities",
  128. "id",
  129. "isActive",
  130. "name",
  131. "dateJoined",
  132. "hasPasswordAuth",
  133. "email",
  134. "options",
  135. )
  136. class RegisterSerializer(BaseRegisterSerializer):
  137. tags = serializers.CharField(
  138. write_only=True,
  139. allow_blank=True,
  140. required=False,
  141. help_text="Additional UTM (analytics) data",
  142. )
  143. def custom_signup(self, request, user):
  144. tags = self.validated_data.get("tags")
  145. if tags:
  146. user.set_register_analytics_tags(tags)
  147. user.save(update_fields=["analytics"])
  148. class UserNotificationsSerializer(serializers.ModelSerializer):
  149. subscribeByDefault = serializers.BooleanField(source="subscribe_by_default")
  150. class Meta:
  151. model = User
  152. fields = ("subscribeByDefault",)
  153. class NoopTokenSerializer(serializers.Serializer):
  154. """dj-rest-auth requires tokens, but we don't use them."""
  155. class PasswordSetResetSerializer(PasswordResetSerializer):
  156. password_reset_form_class = PasswordSetAndResetForm
  157. def save(self):
  158. request = self.context.get("request")
  159. opts = {
  160. "use_https": request.is_secure(),
  161. "from_email": getattr(settings, "DEFAULT_FROM_EMAIL"),
  162. "request": request,
  163. "token_generator": default_token_generator,
  164. "subject_template_name": "registration/password_reset_subject.txt",
  165. "email_template_name": "registration/password_reset_email.txt",
  166. "html_email_template_name": "registration/password_reset_email.html",
  167. }
  168. opts.update(self.get_email_options())
  169. self.reset_form.save(**opts)