serializers.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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.models import EmailAddress
  6. from allauth.account.utils import filter_users_by_email
  7. from allauth.socialaccount.models import SocialApp
  8. from django.conf import settings
  9. from django.utils.translation import gettext_lazy as _
  10. from rest_framework import serializers
  11. from .models import User
  12. class SocialAppSerializer(serializers.ModelSerializer):
  13. authorize_url = serializers.SerializerMethodField()
  14. scopes = serializers.SerializerMethodField()
  15. provider = serializers.SerializerMethodField()
  16. class Meta:
  17. model = SocialApp
  18. fields = ("provider", "name", "client_id", "authorize_url", "scopes")
  19. def get_authorize_url(self, obj):
  20. request = self.context.get("request")
  21. adapter_cls = SOCIAL_ADAPTER_MAP.get(obj.provider)
  22. if adapter_cls == OpenIDConnectAdapter:
  23. adapter = adapter_cls(request, obj.provider_id)
  24. else:
  25. adapter = adapter_cls(request)
  26. if adapter:
  27. return adapter.authorize_url
  28. def get_scopes(self, obj):
  29. request = self.context.get("request")
  30. if request:
  31. provider = obj.get_provider(request)
  32. return provider.get_scope(request)
  33. def get_provider(self, obj):
  34. return obj.provider_id or obj.provider
  35. class ConfirmEmailAddressSerializer(serializers.Serializer):
  36. email = serializers.EmailField()
  37. class EmailAddressSerializer(serializers.ModelSerializer):
  38. isPrimary = serializers.BooleanField(source="primary", read_only=True)
  39. email = serializers.EmailField() # Remove default unique validation
  40. isVerified = serializers.BooleanField(source="verified", read_only=True)
  41. class Meta:
  42. model = EmailAddress
  43. fields = ("isPrimary", "email", "isVerified")
  44. def clean_email(self):
  45. """Validate email as done in allauth.account.forms.AddEmailForm"""
  46. value = self.cleaned_data["email"]
  47. value = get_adapter().clean_email(value)
  48. errors = {
  49. "this_account": _(
  50. "This e-mail address is already associated" " with this account."
  51. ),
  52. "different_account": _(
  53. "This e-mail address is already associated" " with another account."
  54. ),
  55. }
  56. users = filter_users_by_email(value)
  57. on_this_account = [u for u in users if u.pk == self.user.pk]
  58. on_diff_account = [u for u in users if u.pk != self.user.pk]
  59. if on_this_account:
  60. raise serializers.ValidationError(errors["this_account"])
  61. if on_diff_account and app_settings.UNIQUE_EMAIL:
  62. raise serializers.ValidationError(errors["different_account"])
  63. return value
  64. def validate(self, attrs):
  65. if self.context["request"].method == "POST":
  66. # Run extra validation on create
  67. self.user = self.context["request"].user
  68. self.cleaned_data = attrs
  69. attrs["email"] = self.clean_email()
  70. return attrs
  71. def create(self, validated_data):
  72. return EmailAddress.objects.add_email(
  73. self.context["request"], self.user, validated_data["email"], confirm=True
  74. )
  75. def update(self, instance, validated_data):
  76. instance.primary = True
  77. instance.save()
  78. return instance
  79. class UserSerializer(serializers.ModelSerializer):
  80. username = serializers.CharField(source="email", read_only=True)
  81. lastLogin = serializers.DateTimeField(source="last_login", read_only=True)
  82. isSuperuser = serializers.BooleanField(source="is_superuser")
  83. emails = EmailAddressSerializer(many=True, default=[])
  84. id = serializers.CharField()
  85. isActive = serializers.BooleanField(source="is_active")
  86. dateJoined = serializers.DateTimeField(source="created", read_only=True)
  87. hasPasswordAuth = serializers.BooleanField(
  88. source="has_usable_password", read_only=True
  89. )
  90. class Meta:
  91. model = User
  92. fields = (
  93. "username",
  94. "lastLogin",
  95. "isSuperuser",
  96. "emails",
  97. "identities",
  98. "id",
  99. "isActive",
  100. "name",
  101. "dateJoined",
  102. "hasPasswordAuth",
  103. "email",
  104. "options",
  105. )
  106. class CurrentUserSerializer(UserSerializer):
  107. chatwootIdentifierHash = serializers.SerializerMethodField()
  108. def get_chatwootIdentifierHash(self, obj):
  109. if settings.CHATWOOT_WEBSITE_TOKEN and settings.CHATWOOT_IDENTITY_TOKEN:
  110. secret = bytes(settings.CHATWOOT_IDENTITY_TOKEN, "utf-8")
  111. message = bytes(str(obj.id), "utf-8")
  112. hash = hmac.new(secret, message, hashlib.sha256)
  113. return hash.hexdigest()
  114. class UserNotificationsSerializer(serializers.ModelSerializer):
  115. subscribeByDefault = serializers.BooleanField(source="subscribe_by_default")
  116. class Meta:
  117. model = User
  118. fields = ("subscribeByDefault",)