serializers.py 7.6 KB

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