serializers.py 7.5 KB

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